-2 < 1 = false. Why?
Hy! Sorry for my bad engl开发者_如何学JAVAish, anyway the questions is:
I have this code in objective-c:
unsigned int a = 1;
int b = -2
if (b < a);
I expect true and instead the result of the if(b < a)
is false, why?
C automatically converts -2 into an unsigned int in the comparison. The result is that the comparison is actually (4294967294 < 1), which it is not.
You are comparing signed to unsigned. The signed value is promoted to unsigned, which results in a large number (0xFFFFFFFD
I think) which is definitely bigger than 1
The int b is promoted to an unsigned temporary variable in order to do the comparison. This means that it ends up being greater than a.
See here for the rules: http://msdn.microsoft.com/en-us/library/3t4w2bkb(VS.80).aspx
Drop the "unsigned".
If you look at the binary representation of -2 and then use that binary value as an unsigned int, then b>a
Hope that helps!
You can't compare signed and unsigned numbers like that. Most likely the unsigned gets promoted to a signed value resulting in either undefined behaviour or a really big number (depending on how the negative value was stored).
精彩评论