The break and continue statements are control flow statements in C++ that can be used to alter the normal flow of execution of a program.
Break statement
The break statement is used to terminate the execution of the current loop or switch statement. The break statement can be used in any type of loop (for, while, do-while) or switch statement.
Example
The following example shows how to use the break statement to terminate the execution of a for loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
std::cout << i << std::endl;
}
Output:
0
1
2
3
4
The break statement terminates the execution of the for loop when the value of i is equal to 5.
Continue statement
The continue statement is used to skip the remaining statements in the current iteration of the loop and continue with the next iteration. The continue statement can be used in any type of loop (for, while, do-while).
Example
The following example shows how to use the continue statement to skip the remaining statements in the current iteration of a for loop:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i << std::endl;
}
Output:
1
3
5
7
9
The continue statement skips the remaining statements in the current iteration of the for loop when the value of i is even.
Conclusion
The break and continue statements are powerful tools that can be used to control the flow of execution of a program. By using these statements, you can write more efficient and concise code.