Why does counting down an unsigned int loop foreve

2020-02-12 08:03发布

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.

标签: c loops for-loop
5条回答
Anthone
2楼-- · 2020-02-12 08:18

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.

查看更多
Juvenile、少年°
3楼-- · 2020-02-12 08:19

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

查看更多
女痞
4楼-- · 2020-02-12 08:25

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.

查看更多
三岁会撩人
5楼-- · 2020-02-12 08:28

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.

查看更多
Animai°情兽
6楼-- · 2020-02-12 08:29

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.

查看更多
登录 后发表回答