I am reading Carnegie Mellon slides on computer systems for my quiz. In the slide page 49 :
Counting Down with Unsigned
Proper way to use unsigned as loop indexunsigned i; for (i = cnt-2; i < cnt; i--) a[i] += a[i+1];
Even better
size_t i; for (i = cnt-2; i < cnt; i--) a[i] += a[i+1];
I don't get why it's not going to be infinite loop. I am decrementing i
and it is unsigned so it should be always less than cnt
. Please explain.
This appears to be an alternative expression of the established idiom for implementing the same thing
for (unsigned i = N; i != -1; --i)
...;
They simply replaced the more readable condition of i != -1
with a slightly more cryptic i < cnt
. When 0
is decremented in the unsigned
domain it actually wraps around to the UINT_MAX
value, which compares equal to -1
(in the unsigned domain) and which is greater than or equal to cnt
. So, either i != -1
or i < cnt
works as a condition for continuing iterations.
Why would they do it that way specifically? Apparently because they start from cnt - 2
and the value of cnt
can be smaller than 2
, in which case their condition does indeed work properly (and i != -1
doesn't). Aside from such situations there's no reason to involve cnt
into the termination condition. One might say that an even better idea would be to pre-check the value of cnt
and then use the i != -1
idiom
if (cnt >= 2)
for (unsigned i = cnt - 2; i != -1; --i)
...;
Note, BTW, that as long as the starting value of i
is known to be non-negative, the implementation based on the i != -1
condition works regardless of whether i
is signed or unsigned.