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.
Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint's when we know the value we are counting will always be non-negative.
When no negative numbers are required, unsigned integers are well-suited for networking and systems with little memory, because unsigned integers can store more positive numbers without taking up extra memory. New programmers sometimes get signed and unsigned mixed up.
An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].
You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.
Because i
is unsigned
it can't go negative, so i>=0
is always true.
When i
is zero and you do i--
, the value of i
wraps round to the maximum value an unsigned 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.
unsigned int i=10;
while(i --> 0) printf("Hello:%u\n", i+1);
This -->
is referred to sometimes as the goes to operator. But it's in fact just --
and >
. If you change the spacing, you'll get
while( i-- > 0 )
My2c
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.
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.
By defining the i
as unsigned int
you have made it a always non-negative integer therefore all the possible values i
can have are all positive integers (in its range) and 0. Therefore the condition in the loop is always true as i
is always either greater than or equal to 0
therefore it runs infinitely.
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