For Loop - Compare Unsigned Number with Integer

I am trying to compare an unsigned number with a signed number in a for loop, but it does not execute the statement after the for loop, which means the for loop is not working, I think. My code is:

 #include <stdio.h> int main() { unsigned int i; for (i = 8; i >= -1; i--) printf ("%d\n", i); return 0; } 

In the above code, the printf statement is not executed, so something is wrong with my for loop. Can't we compare the unsigned number with the signed number?

+4
source share
2 answers
 unsigned int i; for (i = 8 ; i >= -1; i--) 

-1 converted to the largest value in the unsigned type for comparison. So for unsigned values

 i >= -1 

applicable only for i = UINT_MAX .

To get the given output, the easiest way is to use signed integers, for example. int

Another way is to do some magic in loop control:

 for(i = 8+1; i-- > 0;) 

But if you do, be sure to write a comment explaining the unusual loop control code.

+7
source

It is generally recommended that variables be declared unsigned if they are compared with sizes to avoid this problem.

Compilers give warnings about comparing signature types and unsigned, because the ranges of signed and unsigned ints are different, and when they are compared with each other, the results may be unexpected. If you need to make such a comparison, you must explicitly specify one of the values ​​that will be compatible with the other, perhaps after checking to make sure that the value you are executing is valid.

-1
source

All Articles