C++ break & continue
In this page:
The break Statement
break immediately terminates the loop it's inside, jumping straight to the first line of code after the loop's closing brace, regardless of whether the loop's normal condition would have kept it running. This is typically used to stop searching the moment a target value is found, avoiding wasted iterations.
Example: The break Statement
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The continue Statement
continue skips only the remaining code in the current iteration and jumps straight to the loop's next pass, rather than exiting the loop entirely like break does. It's useful for filtering — for example, skipping over negative numbers in a loop that only needs to process positive ones.
Example: The continue Statement
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
break in Nested Loops
Inside nested loops, break only exits the innermost loop it's directly written in — the outer loop is unaffected and continues iterating normally. If you need to escape multiple nested loops at once, a common approach is a boolean flag checked in the outer loop, since C++ has no built-in labeled break.
Example: break in Nested Loops
#include <iostream>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
std::cout << i << "," << j << " ";
}
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
continue in Nested Loops
Similarly, continue inside a nested loop only skips ahead within the loop it's directly inside, leaving the outer loop's iteration count untouched. This distinction between affecting the inner loop versus the outer loop is a common source of confusion when loops are deeply nested.
Example: continue in Nested Loops
#include <iostream>
int main() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
continue;
}
std::cout << i << "," << j << " ";
}
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Control with User Input
Combining break and continue with conditions based on user input lets a program respond dynamically at runtime — for example, breaking out of an input loop as soon as the user types quit, or using continue to silently skip invalid entries and keep prompting.
Example: Control with User Input
#include <iostream>
int main() {
int hardcodedInputs[] = {3, 5, -1, 7};
for (int i = 0; i < 4; i++) {
int value = hardcodedInputs[i];
if (value < 0) {
break;
}
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: