对于循环条件使用无符号整数时,停在0? [英] For loop condition to stop at 0 when using unsigned integers?
问题描述
我有了从n转到0((含))的循环。我的 I
变量的类型为size_t
通常是无符号的。我目前使用以下code:
I have a loop that has to go from N to 0 (inclusively). My i
variable is of type size_t
which is usually unsigned. I am currently using the following code:
for (size_t i = N; i != (size_t) -1; --i) {
...
}
这是否正确?有没有更好的方式来处理的条件?
Is that correct? Is there a better way to handle the condition?
谢谢,
文森特。
推荐答案
是的,这是正确的,这是一个非常普遍的做法。我不会考虑改变它。
Yes, it's correct and it is a very common approach. I wouldn't consider changing it.
这是无符号整型运算是保证使用模 2 ^ N
算术(其中 N
是多少在类型值位)和溢出行为明确界定。结果被转换成 0
的范围为 2 ^ N - 1
通过增加或减少<$ C $的倍数C> 2 ^ N (即模 2 ^ N
算术)。
Arithmetic on unsigned integer types is guaranteed to use modulo 2^N
arithmetic (where N
is the number of value bits in the type) and behaviour on overflow is well defined. The result is converted into the range 0
to 2^N - 1
by adding or subtracting multiples of 2^N
(i.e. modulo 2^N
arithmetic).
1
转换为无符号整型(其中为size_t
就是其中之一)转换为 2 ^ N - 1
。 -
还采用模 2 ^ N
算术无符号类型,因此无符号类型与值 0
将递减到 2 ^ N - 1
。你的循环终止条件是正确的。
-1
converted to an unsigned integer type (of which size_t
is one) converts to 2^N - 1
. --
also uses modulo 2^N
arithmetic for unsigned types so an unsigned type with value 0
will be decremented to 2^N - 1
. Your loop termination condition is correct.
这篇关于对于循环条件使用无符号整数时,停在0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!