2.1.15 Infinite Loops

Overview

A loop is infinite when its condition keeps permitting another iteration and no reachable action changes that outcome. During debugging, pause execution and inspect the variables that the condition reads. Avoid leaving an application running while investigating a loop that cannot stop.

int count = 0;
while (count < 3)
{
    Console.WriteLine(count);
    // count never changes here.
}
Spot a Missing Exit
A missing update keeps count at zero and repeats the display.
Spot a Missing Exit
  • New
  • Changed
  • Removed

The condition remains true because count stays 0. The display repeats the same value. A correction is to increase count in the body; another is to change the condition when work completes. Adding an unrelated counter does not help unless the loop tests it.

A loop that repeats forever can also result from an update moving in the wrong direction. For example, decreasing count from zero while the condition is count < 3 keeps the condition true. Check not only whether the variable changes, but whether its changes can reach the stopping boundary. Pause the debugger once the pattern is established.

Trace the Outcome

Use a breakpoint in the loop, inspect count for two or three passes, and stop debugging once the repeated state is clear. Explain which statement needs to change the state tested by the condition.

A Missing Update Keeps Reading the Same Cell

This traversal contains a deliberate bug. Predict two passes without running it indefinitely.

Deliberate bug: the index never advances
int[] portions = { 4, 7, 2, 9, 5 };
int index = 0;
while (index < portions.Length)
{
    Console.WriteLine(portions[index]);
    // Missing: index++;
}
Next: display 4. No statement will advance index.
First pass: the first cell
Next: display 4 again. Cells 1 through 4 are never reached.
Second pass: the same cell again

The output is 4, 4, 4, ... because index stays 0. Nothing changes the tested state, so the condition stays true. Stop debugging after confirming the repeated state. Restore index++ inside the body, after the display. The corrected loop visits indexes 0 through 4 and exits at the false check for index 5.