问题
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?
回答1:
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 (your int i), the non qualified type gets promoted to a type of the same type (thus always int), but also inherits the qualifiers of the other quantity (i.e. it becomes unsigned).
When your int, whose value is equal to -2, becames unsigned the first byte undergoes this transformation: 0000 0010 -> 1111 1110. Your int is now a very large positive number, certainly larger of your unsigned int.
There is a solution: cast to signed
while(i < (signed) u)
{
// Do something
i++;
}
By the way, probably your compiler should give you a warning.
回答2:
You are comparing a signed and unsigned integer and your problems started there...
Don't do that and it should work just fine.
来源:https://stackoverflow.com/questions/10849724/cannot-enter-in-while-statement