For Loop - Compare Unsigned Number With Signed Integer

c, for-loop

Solution

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.

Problem

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?

Original source