0

I wonder if someone can explain something, I setup a loop where I wanted to count backwards from 10 to 0 :

for(NSUInteger index = 10; index >= 0; index--) {
    NSLog(@"INDEX: %ld", (long)index);
}

This loop runs forever, it does not stop at 0, but keeps going into negative numbers. When I noticed this I changed my code to :

for(NSInteger index = 10; index >= 0; index--) {
    NSLog(@"INDEX: %ld", (long)index);
}

The above works fine, but I am curious, why the first example does not work as the numbers generated are all unsigned integers?

fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • 2
    BTW - change the 1st NSLog to `NSLog(@"INDEX: %u", index);` and you will better see the problem. – rmaddy Apr 11 '14 at 15:15

2 Answers2

2

An unsigned type can't "keep going into negative numbers". After the iteration when index = 0, index-- becomes 0xFFFFFFFF, which is still more than zero. Easy mistake to make, I've done it myself.

The static analyzer will actually warn you about this ("Condition index >= 0 is always true" or such like.) I highly recommend setting it to run automatically on debug builds.

rgeorge
  • 7,385
  • 2
  • 31
  • 41
  • Ah I see, so because its "unsigned" its always >= 0 (unsigned) even when the logged value says "-10". I get it now, many thanks for taking the time to explain, much appreciated. Static Analyzer was on, but I did not see the warning, I see it now. – fuzzygoat Apr 11 '14 at 14:48
  • 1
    yeah, the NSLog line is casting the unsigned back to signed, so it regains its negativity. Using NSLog(@"INDEX: %@", @(index)); is a tiny bit more reliable since it dodges sprintf's casting limitations. – rgeorge Apr 11 '14 at 19:55
1

Note that an NSUInteger is always >= 0, by consequence, your loop condition will always be true.

bsarr007
  • 1,914
  • 14
  • 14