C++ Break vs Continue: Key Differences
In C++, break and continue are two control flow statements used to control the execution flow of a program within loops.
- The break statement is used to terminate the execution of the current loop (such as for, while, do-while, etc.) and exits the code block following the loop. Once the break statement is executed, the program will exit the loop and continue executing the code after the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
In the example above, the break statement will be executed and the loop will be exited when i is equal to 5.
- The continue statement is used to stop the current iteration in a loop and move on to the next iteration. In other words, when the continue statement is executed, the program will skip the code after continue in the current iteration and move directly to the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << i << endl;
}
In the example above, when i equals 5, the continue statement will be executed, skipping the current iteration and directly moving on to the next one.
Therefore, ‘break’ is used to completely stop the execution of a loop, while ‘continue’ is used to stop the current iteration and move on to the next one.