cfor-loopcharinfinite-loop

Why does the following C code enter an infinite loop?


#include <stdio.h>

int main() {
    for (char c=0; c<128; c++) {
        printf("%c", c);
    }
}

The output of the code prints the whole character list over and over again.

But I also tried running this code:

#include <stdio.h>

int main() {
    for (char c=0; c<127; c++) {
        printf("%c", c);
    }
}

The only change being the condition. It now runs fine without entering an infinite loop.
What is the reason for this?


Solution

  • In C, it is implementation-defined if the char type behaves like signed char or unsigned char. If it behaves like signed char, it can only hold values between -128 to 127 inclusive. Your for loop tries to go to 128, but because char can only hold up to 127, it will never reach 128.

    The condition validation checks if c < 128, and stops when c == 128. When c = 127, the loop progresses making c + 1 = -128. So it loops again and again, and never stops because it never reaches 128.

    Your second loop stops at 127 because the char structure can hold up to 127, so the condition is fulfilled and the loop ends.