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^Narithmetic (whereNis the number of value bits in the type) and behaviour on overflow is well defined. The result is converted into the range0to2^N - 1by adding or subtracting multiples of2^N(i.e. modulo2^Narithmetic).-1converted to an unsigned integer type (of whichsize_tis one) converts to2^N - 1.--also uses modulo2^Narithmetic for unsigned types so an unsigned type with value0will be decremented to2^N - 1. Your loop termination condition is correct.