Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 882
gnuvince Avatar asked Aug 14 '10 17:08

gnuvince


1 Answers

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.

like image 167
CB Bailey Avatar answered Oct 14 '22 06:10

CB Bailey