gnuvince - 11 months ago 57

C Question

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

`i`

`size_t`

`for (size_t i = N; i != (size_t) -1; --i) {`

...

}

Is that correct? Is there a better way to handle the condition?

Thanks,

Vincent.

Answer Source

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.