nagaradderKantesh
nagaradderKantesh

Reputation: 1690

For Loop - Compare Unsigned Number With Signed Integer

I am trying to compare an unsigned number with a signed number in a for loop, but it is not executing 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 code above, the printf statement is not getting executed, so what is wrong with my for loop. Can't we compare an unsigned number with a signed number?

Upvotes: 4

Views: 412

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183978

unsigned int i;
for (i = 8 ; i >= -1; i--)

-1 is converted to the largest value in an unsigned type for the comparison. Thus, for unsigned values,

i >= -1

is only true for i = UINT_MAX.

To get the intended output, the simplest way is to use signed integers, e.g. int.

Another way is to do a bit of magic in the loop control:

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

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

Upvotes: 7

Avio
Avio

Reputation: 29

It is usually a good idea to declare variables as unsigned if they will be compared to sizes, to avoid this issue.

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly cast one of the values to be compatible with the other, perhaps after checking to ensure that the value you are casting is valid.

Upvotes: -1

Related Questions