Ahana Pradhan
Ahana Pradhan

Reputation: 117

Why this piece of code results infinite loop

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

Answers (3)

user1353535
user1353535

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

user694733
user694733

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

Michal
Michal

Reputation: 2238

Unsigned int - its always interpreted as >= 0

Upvotes: 6

Related Questions