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 loop is simply relying on the fact that i
will be decremented past 0, which makes it the max uint value. Which breaks the loop because now i < cnt == false
.
Per Overflowing of Unsigned Int:
unsigned numbers can't overflow, but instead wrap around using the properties of modulo.
Both the C and C++ standard guarantee this uint wrapping behavior, but it's undefined for signed integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With