gnuvince gnuvince - 1 month ago 12
C Question

For loop condition to stop at 0 when using unsigned integers?

I have a loop that has to go from N to 0 (inclusively). My

variable is of type
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.

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.