2.1.14 Stopping a Loop With Break

Video: Control-Break Loops (16:19)
Overview

A break; inside a loop exits the nearest loop immediately. In a Zoo search, a keeper can stop counting after finding the target animal. The code after the loop runs next. This is distinct from return, which ends the entire method.

int position = 0;
while (position < 5)
{
    if (position == 2)
    {
        break;
    }
    position++;
}
Exit Early When the Goal Is Met
Exit Early When the Goal Is Met. A break; inside a loop exits the nearest loop immediately.
Exit Early When the Goal Is Met
  • New
  • Changed
  • Removed

The loop checks positions 0 and 1, then reaches 2. The break runs before the increment and exits the loop with position still 2. It does not mean the while condition became false. Without the break, the loop would continue toward 5.

A loop can exit through its normal false condition or through break. Record which exit occurred; they are not equivalent explanations even if the same later code runs. In the example, position 2 still satisfies position < 5, so the early exit must be attributed to break. If there are nested loops, break applies only to the innermost loop containing it.

Trace the Outcome

Trace the position for each entry to the loop and identify the exit reason. PlantUML break here means leave the loop, just as C# break does.