NSUInteger in reversed loop confusion?

社会主义新天地 提交于 2019-12-20 06:26:52

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/23015452/nsuinteger-in-reversed-loop-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!