Question

When I execute the following loop :

 unsigned m;
 for( m = 10; m >= 0; --m ){
        printf("%d\n",m);
    }

the loop doesn't stop at m==0, it keeps executing interminably, so I thought that reason was that an unsigned cannot be compared to 0. But when I did the following test

unsigned m=9;
if(m >= 0)
    printf("m is positive\n");
else
    printf("m is negative\n");

I got this result:

m is positive 

which means that the unsigned variable m was successfully compared to 0.
Why doesn't the comparison of m to 0 work in the for loop and works fine elsewhere?

Was it helpful?

Solution

You should compile with all warnings enabled.

A test like m >= 0 is always true if m is unsigned; so

if(m >= 0)
  printf("m is positive\n");
else
  printf("m is negative\n");

can be optimized as

printf("m is positive\n");

A recent version of GCC, invoked as gcc -Wall (or gcc -Wall -O1) would have warned you.

And a test like m >0 is the same as m != 0 (or just m)

And your for ( m = 10; m >= 0; --m ) loop is understood as for(m=10; TRUE; --m) so loops indefinitely. Mabye you wanted for (m=10; (int)m>=0; m--) , then the test would fail when m becomes large enough to not fit in an int (without overflow to negative int). But such a (int)m>=0 is ugly and unreadable, so avoid it.

Licensed under: CC-BY-SA with attribution
scroll top