Topic 20 of 83
Break & Continue
Overview
Jump statements alter normal loop execution. `break` completely exits the loop, while `continue` skips the current iteration and proceeds to the next one.
Syntax
cpp
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // Skips printing 3
if (i == 7) break; // Stops the loop entirely
cout << i << " ";
}
// Output: 0 1 2 4 5 6Common Pitfalls
- Using `break` outside of a loop or switch statement (compile error).
- Overusing jump statements can make code harder to read and trace (spaghetti code).
Interview Tips
- Note that `break` only exits the *innermost* loop it is inside. To break out of nested loops, you must use flags or a `goto` statement (though `goto` is highly discouraged).
Real-World Example
Searching for a specific item and breaking early to save time.
example
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> data = {12, 45, 9, 23, 78};
int target = 23;
for (int i = 0; i < data.size(); i++) {
if (data[i] == target) {
cout << "Found target at index " << i << endl;
break; // Stop searching once found
}
}
return 0;
}