Possible Duplicate:
Unsigned and signed comparison
unsigned int and signed char comparison
I have a strange behavior when i try to enter in this while statement:
unsigned u = 0;
int i = -2;
while(i < u)
{
// Do something
i++;
}
But it never enters, even if when i set a break point i = -2 and u = 0.
What am I doing wrong? How could i fix this?
It’s because the ANSI C standard defines that whenever there is a comparison between a qualified (your
unsigned int u) and a non qualified type (yourint i), the non qualified type gets promoted to a type of the same type (thus alwaysint), but also inherits the qualifiers of the other quantity (i.e. it becomesunsigned).When your
int, whose value is equal to-2, becamesunsignedthe first byte undergoes this transformation:0000 0010 -> 1111 1110. Yourintis now a very large positive number, certainly larger of yourunsigned int.There is a solution: cast to
signedBy the way, probably your compiler should give you a warning.