C++ Break/Continue

C++ Break and Continue

Sometimes you need to alter the flow of a loop by either stopping it entirely or skipping an iteration.

The break Statement

You have already seen the break statement used in an earlier chapter of this tutorial (in the switch statement). It can also be used to jump out of a loop.

Example

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break; // Loop stops when i is 4
  }
  cout << i << "\n";
}

The continue Statement

The continue statement breaks one iteration in the loop (if a specified condition occurs), and continues with the next iteration in the loop.

Example

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue; // Skips the rest of the loop block when i is 4
  }
  cout << i << "\n";
}

These two statements give you precise control over how your loops behave in real-time scenarios.


Exercise

?

Which statement is used to skip the rest of the current loop iteration and move to the next one?