break and continue statements
Both the break and continue statements can be used in loops but with very different semantics. In the code examples presented, nested loops will be used to contrast the labeled versions with the non-labeled versions. We will start with the break statement.
break statements
We have already encountered break in switch statements. When used in a loop, the loop exits immediately. Figure 5.17 presents nested for loops with a break in the inner loop.
Figure 5.17 – Showing break inside a loop
In this figure, the outer loop, controlled by i, loops from 1 to 3 in steps of 1. The inner loop, controlled by j, loops from 1 to 5 in steps of 1.
The if statement on line 16 becomes true when j is 3. At this point, the break statement on line 17 is executed. A break without a label exits the nearest enclosing loop. In other words, the break on line 17 refers to the loop on line 15 (controlled by j). As there is no code between...