What's the best way to do a reverse 'for' loop with an unsigned index? What's the best way to do a reverse 'for' loop with an unsigned index? c c

What's the best way to do a reverse 'for' loop with an unsigned index?


How about:

for (unsigned i = n ; i-- > 0 ; ){  // do stuff with i}


for ( unsigned int loopIndex = n; loopIndex > 0; --loopIndex ) {    unsigned int i = loopIndex - 1;    ...} 

or

for ( unsigned int loopIndex = 0; loopIndex < n; ++loopIndex ) {    unsigned int i = n - loopIndex - 1;    ...} 


for ( unsigned int i = n; i != 0; i-- ) {    // do something with i - 1    ...     }

Note that if you use C++ as well as C, using != is a good habit to get into for when you switch to using iterators, where <= etc. may not be available.