Consider this C code:
#include "stdio.h"
int main(void) {
int count = 5;
unsigned int i;
for (i = count; i > -1; i--) {
printf("%d\n", i);
}
return 0;
}
My observation/question: the loop never gets executed. But if I change the data type of i from unsigned int to int, everything works as expected.
I've been thinking of unsigned ints as values that "wrap around" when you try to keep subtracting from them. So, when i is zero and I subtract 1, it would wrap around to UINT_MAX. And since its value is never negative, this would be effectively an endless loop. (And this is exactly what happens when I change the comparison from i > -1 to i >= 0.)
There is a fault somewhere in my logic, as the loop never gets executed if i is unsigned, and I'm comparing it to -1. Either the compiler optimizes it away somehow or the runtime values behave differently from what I expect.
Why does the loop not get run?