Lesson 75 +10 XP

Break and Continue

Two small statements give you extra control inside a loop: break and continue.

break ends the loop

break stops the loop immediately. Execution jumps to the first line after the loop and keeps going from there.


cpp
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  cout << i << endl;
}

This prints 0, 1, 2, 3 and then stops, even though the loop was set to run ten times.

continue skips the iteration

continue skips only the rest of the current run and jumps straight to the next iteration. The loop itself keeps going.


cpp
for (int i = 0; i < 5; i++) {
  if (i == 2) {
    continue;
  }
  cout << i << endl;
}

This prints 0, 1, 3,

  1. The number 2 is skipped, but the loop carries on.

One exits, one skips

LearnCpp 8.11 sums it up: break leaves the loop for good; continue only abandons the current pass.

TL;DR

  • break ends the loop entirely.
  • continue skips the rest of the current iteration only.
  • After a break, execution resumes a line after the loop.
  • Use them to cut a loop short or dodge a single case.