C++ ยท Chapter 19 of 49

C++ Break and Continue

The `break` statement immediately exits the nearest enclosing loop or switch, while `continue` skips the rest of the current iteration and jumps to the next one.

Both are useful for handling special cases inside loops without deeply nesting if statements.

break

`break` stops the loop entirely โ€” execution continues right after the loop's closing brace. It's commonly used to exit early once a search finds what it's looking for.

continue

`continue` skips only the current iteration, moving straight to the loop's increment/condition check, useful for filtering out unwanted values.

Example 1 (cpp)
for (int i = 0; i < 5; i++) {
    if (i == 3) break;
    std::cout << i;
}
Output
012

The loop stops entirely once i equals 3.

Example 2 (cpp)
for (int i = 0; i < 5; i++) {
    if (i % 2 == 0) continue;
    std::cout << i;
}
Output
13

continue skips even numbers, printing only odd ones.

Key points

  • break exits the loop or switch entirely.
  • continue skips to the next iteration.
  • Both only affect the nearest enclosing loop.
  • Overusing them can hurt readability โ€” use sparingly.
๐Ÿ’ก Note: In nested loops, break/continue only affect the innermost loop unless you use labels/goto (rare in modern C++).

๐Ÿ“ Quick Quiz

1. Which statement exits a loop completely?

2. Which statement skips to the next iteration?

3. break inside nested loops affects: