Reputation: 117
unsigned int i = 1<<10;
for(; i>=0; i--) printf(“%d\n”, i);
Can anyone please explain the reason why this code results in infinite loop? Thanks in advance for any response.
Upvotes: 4
Views: 166
Reputation: 681
Reason why it results in an infinite loop is already explained by other answers. However to achieve the intended behaviour of your code, counting down from 1024 to 0 using unsigned int, try this instead.
unsigned int i = (1<<10)+1;
for(;i-- > 0;) printf(“%d\n”, i);
Note that the value of i after the loop will be the rolled over value.
Upvotes: 1
Reputation: 16047
Unsigned integers are always positive. When i == 0
and you decrement 1
from it, result will wrap-around to maximum unsigned int
value UINT_MAX
, because your data type cannot handle negative values.
Upvotes: 4