C++ Break and Continue Statements
Introduction to Loop Control
The break
and continue
statements provide fine-grained control over loop execution.
break
exits a loop immediately, while continue
skips the rest of the current iteration and jumps to the next cycle.
break Statement
The break
statement ends the loop as soon as it is encountered, regardless of the loop condition.
Example
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
cout << "Breaking at " << i << endl;
break;
}
cout << i << " ";
}
cout << "\nLoop ended";
return 0;
}
Output
1 2 3 4 Breaking at 5 Loop ended
ℹ️ Note: The break statement works with all loop types (`for`, `while`, `do-while`) and also with `switch` statements.
continue Statement
The continue
statement skips the remaining code in the current iteration and starts the next loop cycle.
⚠️ Warning: In `while` or `do-while` loops, make sure loop variables are updated properly before `continue`, otherwise infinite loops may occur. In a `for` loop, `continue` jumps to the increment step, then the condition is rechecked.
Example
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
cout << i << " ";
}
return 0;
}
Output
1 3 5
Nested Loop Control
`break` and `continue` only affect the innermost loop in which they appear.
Example
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
cout << "\nBreaking inner loop\n";
break; // exits only the inner loop
}
cout << "(" << i << "," << j << ") ";
}
}
return 0;
}
Output
(1,1) (1,2) (1,3) (2,1) Breaking inner loop (3,1) (3,2) (3,3)
Practical Examples
Common use cases of break and continue include:
Scenario | Statement | Reason |
---|---|---|
Input validation | break | Exit loop once valid input is received |
Search algorithm | break | Stop searching when the target is found |
Data filtering | continue | Skip unwanted or invalid records |
Menu systems | break | Exit a loop-based menu selection |
Best Practices
- Use break and continue sparingly; overuse can reduce readability.
- Prefer clear loop conditions instead of multiple breaks.
- Comment control flows that are not obvious.
- When affecting outer loops, consider using flags or restructuring logic.
- Avoid mixing break/continue with overly complex loop logic.
Example
// Example with multiple breaks
bool found = false;
for (auto item : collection) {
if (condition1) {
found = true;
break;
}
if (condition2) {
found = true;
break;
}
}
// Clearer version:
for (auto item : collection) {
if (condition1 || condition2) {
found = true;
break;
}
}