NSUInteger是否在反向循环中感到困惑? [英] NSUInteger in reversed loop confusion?

查看:87
本文介绍了NSUInteger是否在反向循环中感到困惑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以解释一些问题,所以我设置了一个循环,希望从10倒数到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);
}

此循环永远运行,它不会在0处停止,但会一直变为负数.当我注意到这一点时,我将代码更改为:

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?

推荐答案

无符号类型不能保持负数".在index = 0的迭代之后,index--变为0xFFFFFFFF,仍然大于零.容易犯的错误,我自己做了.

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.

静态分析器实际上会警告您(条件索引> = 0始终为真"或类似的东西.)我强烈建议将其设置为在调试版本中自动运行.

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.

这篇关于NSUInteger是否在反向循环中感到困惑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆