5
votes

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.

5
Could you show the rest of your code it may be memory corruption before , or even buffer overflow of one of the function parameters - Sergey Kucher
@Sergey: I don't think you're right there - it's just a bug. See the answers. - RichieHindle
your loop condition is waiting for an unsigned int to be negative... how can that be even possible? - Yanick Rochon

5 Answers

10
votes

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.

7
votes

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

3
votes

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.

1
votes

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.

1
votes

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.