Published on Micro Basics (http://www.ubasics.com)

One safe way to decrement an unsigned in a for loop

By stienman
Created Apr 29 2009 - 10:51pm

don.neufeld points out [1] that there's only one safe way to use a for loop to decrement an unsigned int to 0:

for( i = n; i-- > 0; )
{
// Use i as normal here
}

"There's a trick here, for the last loop iteration you will have i = 1 at the top of the loop, i-- > 0 passes because 1 > 0, then i = 0 in the loop body. On the next iteration i-- > 0 fails because i == 0, so it doesn't matter that the postfix decrement rolled over the counter."


Source URL:
http://www.ubasics.com/One_safe_way_to_decrement_an_unsigned_in_a_for_loop