Infinite Loops in C: Why They Happen and How to Stop Them
Your program starts, prints the same line again and again or simply freezes. You have written an infinite loop. In a terminal you can stop a running program with Ctrl+C. Then use this guide to find out why it happened.
Cause 1: the loop variable never changes
int i = 0;
while (i < 5)
{
printf("%d\n", i);
}
The condition i < 5 is always true because nothing inside the loop changes i. Add i++; inside the loop body.
Cause 2: counting in the wrong direction
for (i = 10; i > 0; i++)
{
printf("%d\n", i);
}
The condition wants i to fall toward 0, but i++ makes it grow. Use i-- instead.
Cause 3: = instead of ==
int x = 0;
while (x = 1)
{
/* ... */
}
A single = assigns the value 1, and the result of the assignment is 1, which counts as true. Use == to compare. Compiling with -Wall gives a helpful warning here.
Cause 4: a stray semicolon
int i = 0;
while (i < 5);
{
i++;
}
The semicolon after the condition ends the loop, so its body is empty and i++ never runs. The braces below it are just a separate block.
Cause 5: unsigned counters that count down
unsigned int i;
for (i = 5; i >= 0; i--)
{
printf("%u\n", i);
}
An unsigned number can never be negative. When i reaches 0 and is decreased, it wraps around to a huge positive number, so i >= 0 is always true. Use a signed int or restructure the loop.
Cause 6: comparing floating-point numbers exactly
float x = 0.0f;
while (x != 1.0f)
{
x += 0.1f;
}
The value 0.1 cannot be stored exactly in binary, so after ten additions x is slightly different from 1.0 and the loop sails past it. Count with an integer instead, or compare using a small tolerance.
When infinite loops are intentional
Servers, games and embedded programs often run forever on purpose. They use while (1) with a clear way out.
while (1)
{
int ch = getchar();
if (ch == 'q' || ch == EOF)
{
break;
}
}
How to debug a loop that will not stop
- Print the loop variable inside the loop for a moment to see how it changes
- Run the program in
gdb, pressCtrl+Cwhile it is stuck and typebtto see where it is - Compile with
-Wall -Wextraand read every warning - Re-read the condition out loud: "keep going while this is true"
Loops can also fail in the opposite way, by running one time too many or too few. That is the subject of our guide to off-by-one errors. To practice loops step by step, our C Programming notes cover while, for, do-while and nested loops with examples.