C++ Reference ยท Keywords and Statements
The break and continue statements
Reference for C++ break and continue: leaving or skipping loop iterations, break inside switch, escaping nested loops, and where each one jumps.
break ends the innermost enclosing loop (for, range-for, while, do) or switch statement immediately. Execution continues with the statement after it. continue skips the rest of the current iteration of the innermost loop and goes on to the next one.
Both only affect the nearest enclosing construct. C++ has no labeled break, so leaving several nested loops at once needs a different tool: a function with return, a flag, or goto.
for (int i = 0; i < 10; ++i) { if (i == 3) continue; // skip 3 if (i == 6) break; // stop at 6 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
break; continue;
| Statement | Effect |
|---|---|
break; |
Valid inside a loop body or a switch. Control moves to the statement following the innermost loop or switch. |
continue; |
Valid inside a loop body only. In a for the step expression runs next; in while and do-while the condition is tested next. |
Usage notes
breakoutside a loop or switch is a compile error, and so iscontinueoutside a loop (aswitchalone does not count).- Inside a
switchthat sits within a loop,continueapplies to the loop andbreakto the switch. This catches many people out. - Destructors of local objects declared inside the loop body run when you
breakorcontinue, so RAII cleanup is safe. - In a
whileloop, put the update before acontinue; otherwise the loop may never finish. - Extracting the loop into a function and using
returnis usually clearer than a flag variable orgotofor leaving nested loops. - Standard algorithms such as
std::find_iforstd::ranges::any_ofoften replace a loop that exists only tobreakat the first match. - A lambda cannot
breakthe loop that calls it; return a value and let the caller decide.
Related
- for
- while and do-while
- switch
- goto
- Tutorial: break, continue and goto