A break statement is commonly used to terminate the execution of a loop. When loops are used in conjunction with switch or select, developers frequently make the mistake of breaking the wrong statement.
Let’s take a look at the following example. We implement a switch inside a for loop. If the loop index has the value 2, we want to break the loop:
This code may look right at first glance; however, it doesn’t do what we expect. The break statement doesn’t terminate the for loop: it terminates the switch statement, instead. Hence, instead of iterating from 0 to 2, this code iterates from 0 to 4: 0 1 2 3 4.
One essential rule to keep in mind is that a break statement terminates the execution of the innermost for, switch, or select statement. In the previous example, it terminates the switch statement.
So how can we write code that breaks the loop instead of the switch statement? The most idiomatic way is to use a label:
Here, we associate the loop label with the for loop. Then, because we provide the loop label to the break statement, it breaks the loop, not the switch. Therefore, this new version will print 0 1 2, as we expected.