4

Hy! Sorry for my bad english, 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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Antonio Barra
  • 249
  • 1
  • 3
  • 7
  • does objective c interpret negative integers as positive? maybe? – tekknolagi Jan 13 '11 at 00:35
  • Type unsigned integer type can't hold negative numbers. Use a debugger to see the actual value in B, you'll see it is not -2 – Sparky Jan 13 '11 at 00:35
  • 6
    Guessing that -2 gets cast to unsigned and becomes a very big number. – Martin Smith Jan 13 '11 at 00:35
  • Answer with explanation is already here in this link http://stackoverflow.com/questions/2084949/arithmetic-operations-on-unsigned-and-signed-integers – Nike Jan 13 '11 at 00:42

5 Answers5

9

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.

EmeryBerger
  • 3,897
  • 18
  • 29
7

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
SRM
  • 1,377
  • 1
  • 10
  • 17
3

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

sashang
  • 11,704
  • 6
  • 44
  • 58
2

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!

Alex
  • 4,316
  • 2
  • 24
  • 28
0

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).

orlp
  • 112,504
  • 36
  • 218
  • 315