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?
Thanks,
Vincent.
Yes, it's correct and it is a very common approach. I wouldn't consider changing it.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With