Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to count down with unsigned

Tags:

c

loops

unsigned

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 index

unsigned 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.

like image 961
Kalia Dona Avatar asked Dec 15 '22 00:12

Kalia Dona


1 Answers

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.

like image 195
Drakestar Avatar answered Dec 31 '22 05:12

Drakestar