The below code runs in an infinte loop. 'i' has been intialised with the value 1 and then compared with 0.
So printf() stmt should execute once but it runs infinetly.
unsigned int i = 1;
for (; i >= 0; i--) {
printf("Hello: %u\n",i);
}
please explain this behaviour.
Because
i
isunsigned
it can't go negative, soi>=0
is always true.When
i
is zero and you doi--
, the value ofi
wraps round to the maximum value anunsigned int
can have (which is greater than zero).You should use a signed integer, by removing the
unsigned
modifier.As other answers said, it's because it's unsigned and all. I will tell you an elegant way to do what you want to do with an unsigned integer.
This
-->
is referred to sometimes as the goes to operator. But it's in fact just--
and>
. If you change the spacing, you'll getMy2c
It's an
unsigned int
. Decrementing it from 0 will not yield -1.To achieve your intended goal, you need to drop the
unsigned
qualifier. This will remedy the integer overflow causing the observed behavior.By defining the
i
asunsigned int
you have made it a always non-negative integer therefore all the possible valuesi
can have are all positive integers (in its range) and 0. Therefore the condition in the loop is always true asi
is always either greater than or equal to0
therefore it runs infinitely.The standard says for unsigned integers if the result would go below zero you add 2^n where n is the number of bits in the representation.
Since the integer is unsigned, the compiler will optimize this to an infinite loop.