C++ Break and Continue
Sometimes you need to escape a loop early, or skip just one awkward pass without stopping everything. That is exactly what break and continue are for. These two small keywords give you fine control over the flow of any loop, and they work with while, do/while, and for loops alike.
The break statement
The break statement immediately ends the loop it is inside. As soon as break runs, the loop stops completely and your program jumps to the first line after the loop, ignoring any remaining passes.
Stop the loop early
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}This loop was set up to run until i reaches 10, but break ends it the moment i equals 4. So it prints 0, 1, 2, and 3, then quits without printing anything else.
The continue statement
The continue statement skips the rest of the current pass and jumps straight to the next one. The loop itself keeps going; only the leftover code in that single pass is skipped.
Skip one value
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 6; i++) {
if (i == 3) {
continue;
}
cout << i << "\n";
}
return 0;
}Here every number from 0 to 5 is printed except 3. When i equals 3, continue skips the cout line for that pass only, and the loop moves on to i equals 4.
- break exits the whole loop right away.
- continue skips to the next pass of the same loop.
- Both usually appear inside an if so they trigger only under a specific condition.
Exercise: C++ Break and Continue
What does a break statement do inside a loop?