What is the difference between continue and break in C+…
In C++, continue and break are two control flow statements used to alter the way loops are executed.
The break statement is used to immediately terminate the current loop structure (such as a for, while, or do-while loop), and jump out of that loop to execute the statements after the loop. Once the break statement is executed, any remaining statements inside the loop body will not be executed, and instead the program will directly move to the next statement after the loop structure. In other words, the break statement is used to completely end the loop.
Here is an example of using the break statement:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
cout << i << " ";
}
In the above code, when the value of i is equal to 5, the break statement is executed, the loop stops, and outputs 0 1 2 3 4.
The continue statement is used to immediately skip the remaining statements in the current loop structure and continue with the execution of the next iteration. Once the continue statement is executed, it will skip the statements after the continue statement in the loop body and directly move on to the next iteration. In other words, the continue statement is used to terminate the current iteration and move on to the next one.
Here is an example of using the continue statement:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << i << " ";
}
In the code above, when the value of i is equal to 5, the continue statement is executed, skipping the output statement for that iteration and moving to the next one, resulting in the output of 0 1 2 3 4 6 7 8 9.
In conclusion, the break statement is used to completely terminate a loop, while the continue statement is used to skip the current iteration and move on to the next one.