C++ Break and Continue
Sometimes you need to change the normal flow of a loop: stop it early, or skip the rest of the current iteration. That is what break and continue are for. Both work in for, while and do..while loops.
break — leave the loop
break ends the loop immediately. Execution continues with the first statement after the loop. It is perfect for searching: once you have found what you are looking for, there is no point in continuing.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {4, 8, 15, 16, 23, 42};
int target = 16;
int position = -1;
for (int i = 0; i < 6; i++) {
cout << "checking index " << i << "\n";
if (numbers[i] == target) {
position = i;
break;
}
}
cout << "Found " << target << " at index " << position << "\n";
}checking index 0
checking index 1
checking index 2
checking index 3
Found 16 at index 3
continue — skip to the next iteration
continue skips the rest of the current pass and jumps straight to the next one. In a for loop, the update expression (i++) still runs.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
cout << i << " ";
}
cout << "\n";
}1 2 4 5 7 8 10
continue is often used as a guard at the top of a loop body to filter out items you do not want to process, which keeps the main logic un-indented:
#include <iostream>
#include <string>
using namespace std;
int main() {
string lines[] = {"# config file", "width=800", "", "height=600", "# end"};
for (const string& line : lines) {
if (line.empty() || line[0] == '#') {
continue;
}
cout << "setting: " << line << "\n";
}
}setting: width=800
setting: height=600
break in a while (true) loop
A common pattern is an "endless" loop with the exit condition in the middle:
#include <iostream>
using namespace std;
int main() {
int n = 1;
while (true) {
n *= 3;
if (n > 500) {
break;
}
cout << n << " ";
}
cout << "\nstopped at " << n << "\n";
}3 9 27 81 243
stopped at 729
Nested loops
break and continue only affect the innermost loop they appear in. To leave several loops at once, use a flag variable (or move the loops into a function and return):
#include <iostream>
using namespace std;
int main() {
bool found = false;
for (int a = 1; a <= 10 && !found; a++) {
for (int b = a; b <= 10; b++) {
if (a * b == 24 && a + b == 10) {
cout << "a=" << a << ", b=" << b << "\n";
found = true;
break; // leaves only the inner loop
}
}
}
}a=4, b=6
Note: Inside a
switchthat sits in a loop,breakexits the switch, not the loop.continue, on the other hand, applies to the enclosing loop.
Test yourself
What does break do inside a loop?
- Skips the current iteration
- Exits the loop immediately
- Restarts the loop
- Exits the whole program
What does this print? for (int i = 0; i < 5; i++) { if (i == 2) continue; cout << i; }
- 01
- 0134
- 01234
- 234
In nested loops, which loop does break exit?
- All of them
- The outermost loop
- The innermost loop containing it
- None, it is an error