Learn C++
#include "controlflow/break_continue.hpp"

break, continue & goto in C++

//concept

break exits its nearest loop or switch immediately; continue skips the rest of the current iteration and starts the next one. Together they express early exits and skips far more readably than flag variables — search loops (break on found) and filters (continue on bad items) are the canonical shapes.

goto jumps to a label anywhere in the function. It is shunned in application code but survives in one respectable niche: breaking out of nested loops and unified cleanup in C-style error handling, where the alternatives (flags, extra functions) genuinely read worse.

//how it works
1

break exits now

The moment break executes, control jumps past the loop's closing brace — remaining iterations never happen.

2

continue skips ahead

continue abandons only the current pass: for loops still run their step expression, while loops jump straight to the test.

3

Only the innermost loop

In nested loops, break/continue affect the closest enclosing loop — exiting outer loops needs a flag, a function return, or goto.

4

goto's narrow license

Forward jumps to shared cleanup or out of deep nesting are goto's defensible uses; backward jumps that build spaghetti loops are not.

//example
#include <iostream>
#include <vector>
 
int main() {
std::vector<int> v{3, -1, 4, -2, 5};
for (int x : v) {
if (x < 0) continue;
if (x == 4) break;
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
Output
3
13 is non-negative and not 4, so it prints.
2-1 triggers continue, skipping its print and moving to 4.
34 triggers break, ending the whole loop — -2 and 5 are never even examined.
//use cases
Linear search that breaks the moment the target is found
Skipping invalid records in data-processing loops with continue
C-style cleanup jumps (goto done;) in resource-heavy legacy functions
Replacing boolean found-flags with direct break exits

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.