The break and continue operators are used in loop constructs (for, while, do..while) to control the flow of execution.
Nuances:
break inside nested loops will only exit the innermost loop.goto, the logic can be influenced in complex ways.continue in while and do..while loops can cause unexpected control flow changes if the order of operations is not considered.Example:
for (int i = 0; i < 5; ++i) { if (i == 2) continue; if (i == 4) break; printf("%d ", i); } // Outputs: 0 1 3
How will a loop behave with the continue operator if it uses complex expressions during initialization and update of the counter?
Common incorrect answer:
Many believe that when continue is triggered, all expressions within the loop construct (e.g., incrementing in for) are not executed.
Correct answer:
In a for loop, upon reaching continue, the remaining part of the loop body is skipped, but the counter update expression (the third part of the for expression) is still executed:
for (int i = 0; i < 3; printf("step %d ", i), ++i) { if (i == 1) continue; printf("%d ", i); }
Output:
0
step 0
step 1
2
step 2
Story
Inside a loop over an array, continue was used without updating the counter parameter explicitly (in a while loop), which led to an infinite loop.
Story
The nested loop for matching triggered break on the first match, but the programmer expected the entire loop to stop, resulting in incorrect processing of the remaining elements.
Story
In a do..while construct, where the main loop used continue, a key concluding operation was skipped before proceeding to the next iteration, leading to data loss due to incorrect state changes inside the loop body.