Search⌘ K
AI Features

Discussion: It Just Can’t Be Done

Explore the reasons behind infinite loops caused by signed char variables in C. Learn to identify the issue, understand data type ranges, and apply solutions such as using unsigned variables or larger data types to control loops effectively.

Run the code

Now, it's time to execute the code and observe the output.

#include <stdio.h>

int main()
{
  char a;
  for( a=0; a<200; a++ )
    printf("%3d ", a);
  return(0);
  putchar('\n');
  
  return(0);
}
C code for the given puzzle

Understanding the output

Ignoring any error the compiler coughs up, the program outputs an endless loop, cycling from 0 to 127, then from -128 to 0 again. Press "Ctrl+C" to halt the nonsense.

The reason the program results in an endless loop is because the char data type is signed by default in C, with a range of -128 to ...