Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating with size_t 0 as a boundary condition

Tags:

c++

c

What's the "correct" way to write a decreasing loop with a size_t value and a boundary condition. Example incorrect implementation:

for (size_t elemNum = listSize-1; elemNum >= 0; --elemNum) { /* ... */ }

When it reaches zero it will wrap around to the max value rather than acting as a boundary condition. Iterating the loop in reverse is necessary. It seems like a problem that would have a defacto standard solution but I can't find what it is.

like image 904
Mark Langen Avatar asked Aug 28 '11 22:08

Mark Langen


1 Answers

The most succinct approach is to use post-increment:

for (size_t i = listSize; i--;) ...
like image 165
Marcelo Cantos Avatar answered Sep 23 '22 14:09

Marcelo Cantos