Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse iteration with an unsigned loop variable

Tags:

c++

for-loop

I've been discussing the use of size_t with colleagues. One issue that has come up is loops that decrement the loop variable until it reaches zero.

Consider the following code:

for (size_t i = n-1; i >= 0; --i) { ... } 

This causes an infinite loop due to unsigned integer wrap-around. What do you do in this case? It seems far to easy to write the above code and not realise that you've made a mistake.

Two suggestions from our team are to use one of the following styles:

for (size_t i = n-1; i != -1 ; --i) { ... }  for (size_t i = n; i-- > 0 ; ) { ... } 

But I do wonder what other options there are...

like image 218
Daniel Paull Avatar asked Sep 02 '10 01:09

Daniel Paull


2 Answers

Personally I have come to like:

for (size_t i = n; i --> 0 ;) 

It has a) no funny -1, b) the condition check is mnemonic, c) it ends with a suitable smiley.

like image 60
visitor Avatar answered Sep 18 '22 17:09

visitor


Unsigned integers are guaranteed to wrap around nicely. They just implement arithmetic modulo 2N. So an easy to read idiom is this one:

for (size_t i = n-1; i < n ; --i) { ... } 

this sets the variable to the initial value that you want, shows the sense of the iteration (downward) and gives precisely the condition on the values that you want to handle.

like image 29
Jens Gustedt Avatar answered Sep 19 '22 17:09

Jens Gustedt