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.
for (int i = 0; i < 5; i++) {
if (i == 3) break;
std::cout << i;
}012The loop stops entirely once i equals 3.
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) continue;
std::cout << i;
}13continue 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.
