My first attempt of reverse for loop that does something n times was something like:
for ( unsigned int i = n-1; i >= 0; i-- ) {
...
}
This fails because in unsigned arithmetic i
is guaranteed to be always greater or equal than zero, hence the loop condition will always be true. Fortunately, gcc compiler warned me about a 'pointless comparison' before I had to wonder why the loop was executing infinitely.
I'm looking for an elegant way of resolving this issue keeping in mind that:
How about:
for (unsigned i = n ; i-- > 0 ; )
{
// do stuff with i
}