Break & Continue
Overview
Sometimes, standard loop conditions aren't enough. You might be searching through a massive database of 1 million users for a specific ID. If you find the user on iteration 5, it is a catastrophic waste of CPU power to allow the loop to run 999,995 more times.
C++ provides two powerful loop control keywords. break instantly murders the loop, completely escaping its curly braces and continuing with the rest of the program. continue is less destructive; it instantly aborts the current iteration, skips any code remaining in the loop block, and immediately forces the loop to start the next iteration.
Syntax
for (int i = 1; i <= 10; i++) {
// 1. CONTINUE: Skip the rest of this specific iteration
// If the number is even, skip printing it!
if (i % 2 == 0) {
continue;
}
std::cout << i << " ";
// 2. BREAK: Completely escape the loop entirely
// If we hit 7, destroy the loop!
if (i == 7) {
break;
}
}
// Output will be: 1 3 5 7Common Pitfalls
- Using
breakin deeply nested loops. If you have aforloop inside anotherforloop, callingbreak;only destroys the inner loop. The outer loop will continue running normally. To break out of both, you usually need to utilize a boolean flag. - Dead Code after a
continue. Any code physically written below acontinuestatement inside the loop block will be completely ignored for that iteration. Beginners often place vital update logic below acontinue, causing infinite loops.
Interview Questions
break and continue keywords be used interchangeably inside switch statements and while loops?No. While break is universally used to escape both loops and switch statements, continue is strictly limited to looping constructs (for, while, do...while). Attempting to use continue inside a raw switch statement (that isn't wrapped in a loop) will result in a fatal compilation error.
Real-World Example
Using break to vastly optimize a Linear Search algorithm.
int database[] = {42, 19, 88, 7, 50};
int target = 88;
bool found = false;
for (int i = 0; i < 5; i++) {
if (database[i] == target) {
found = true;
// CRITICAL OPTIMIZATION: We found it!
// Stop searching the rest of the array immediately!
break;
}
}Check Your Knowledge
Test your understanding of Break & Continue with these quick questions.