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...
Here is a pointer to a good discussion on this topic.
I would try:
Personally I have come to like:
It has a) no funny
-1
, b) the condition check is mnemonic, c) it ends with a suitable smiley.i-1
instead ofi
.Yet another way (no signed/unsigned comparisons):
since
If you're worried about accidentally writing a loop like that, some compilers will warn about such things. For example, gcc has a warning enabled by the
-Wtype-limits
option (also enabled by-Wextra
):Are you using standard library containers? If so I like
reverse_iterator
For a raw array you can just use a
std::reverse_iterator
the key to this is that a pointer is an iterator:Noncontiguous object iteration can be done by storing the object pointers in a container or array:
If you really want to use a naked
size_t
then why use all of this implicitly confusing -1 trickery in the other answers? The max value ofsize_t
is explicitly available to use as your termination value: