2

Can you explain me why this code:

NSInteger i = -1;
NSUInteger x = 1;
NSLog(@"min = %lu", MIN(i, x));
NSLog(@"max = %lu", MAX(i, x));;

prints min = 1

max = 18446744073709551615

rmaddy
  • 314,917
  • 42
  • 532
  • 579
SergStav
  • 750
  • 5
  • 19

3 Answers3

1

You compare two different types: signed (NSInteger) and unsigned (NSUInteger). MIN/MAX convert all to unsigned integer.

Moreover, negative NSInteger is printed with %lu instead of %du. Therefore see a big number.

NSInteger i = -1;
NSUInteger x = 1;
NSLog(@"min = %ld", MIN(i, (NSInteger)x));
NSLog(@"max = %ld", MAX(i, (NSInteger)x));
Danil Valeev
  • 211
  • 1
  • 6
0

It's because i is actually being converted into an unsigned int implicitly. See here. As a result it rolls over to 18446744073709551615.

Community
  • 1
  • 1
Gordonium
  • 3,389
  • 23
  • 39
0

It is because i is being implicitly converted to an unsigned long. It is part of the way xcode handles integer conversions. Here is a similar post. NSUInteger vs NSInteger, int vs unsigned, and similar cases

Community
  • 1
  • 1