Why does an unsigned int loop end in C forever?

Below code works in infinte loop. "i" was indexed with a value of 1, and then compared with 0.

So printf () stmt should run once, but it runs endlessly.

unsigned int i=1; for(;i>=0;i--) printf("Hello:%u\n",i); 

please explain this behavior.

+4
source share
5 answers

As the other answers said, this is because it is unsigned and that’s it. I will tell you about 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 --> sometimes referred to as going to . But actually it’s simple -- and > . If you change the interval, you will get

 while( i-- > 0 ) 

My2c

+7
source

Since i is unsigned , it cannot be negative, therefore i>=0 always true.

When i is zero and you execute i-- , the value of i rounded to the maximum value a unsigned int may have (which is greater than zero).

You must use a signed integer by removing the unsigned modifier.

+9
source

This is a unsigned int . Decreasing it from 0 will not yield -1.

To achieve the intended goal, you need to drop the unsigned qualifier. This will eliminate the integer overflow , causing the observed behavior.

+3
source

The standard says for unsigned integers, if the result is below zero, you add 2 ^ n, where n is the number of bits in the view.

Since it is an unsigned integer, the compiler optimizes it to an infinite loop.

+1
source

By defining i as an unsigned int , you made it always a non-negative integer, therefore all possible values ​​of i can have all positive integers (in its range) and 0. Therefore, the condition in the loop is always true, since i always either greater than or equal to 0 , therefore It works endlessly.

+1
source

All Articles