break
and continue
StatementsIn addition to selection and iteration statements, C++ provides statements break
(which we discussed in the context of the switch
statement) and continue
to alter the flow of control. The preceding section showed how break
can be used to terminate a switch
statement’s execution. This section discusses how to use break
in iteration statements.
break
StatementThe break
statement, when executed in a while
, for
, do
…while
or switch
, causes immediate exit from that statement—execution continues with the first statement after the control statement. Common uses of the break
statement are to escape early from a loop or to skip the remainder of a switch
(as in Fig. 5.11). Figure 5.13 demonstrates a break
statement exiting a for
.
When the if
statement nested at lines 10–12 in the for
statement (lines 9–15) detects that count
is 5
, the break
statement at line 11 executes. This terminates the for
statement, and the program proceeds to line 17 (immediately after the for
statement), which displays a message indicating the value of the control variable when the loop terminated. The loop fully executes its body only four times instead of 10.
continue
StatementThe continue
statement, when executed in a while
, for
or do
…while
, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In while
and do
…while
statements, the program evaluates the loop-continuation test immediately after the continue
statement executes. In a for
statement, the increment expression executes, then the program evaluates the loop-continuation test.
Figure 5.14 uses continue
(line 9) to skip the statement at line 12 when the nested if
determines that count
’s value is 5
. When the continue
statement executes, program control continues with the increment of the control variable in the for
statement (line 7).
In Section 5.3, we stated that while
could be used in most cases in place of for
. This is not true when the increment expression in the while
follows a continue
statement. In this case, the increment does not execute before the program evaluates the iteration-continuation condition, so the while
does not execute in the same manner as the for
.
Some programmers feel that break
and continue
violate structured programming. Since the same effects are achievable with structured-programming techniques, these programmers do not use break
or continue
.
There’s a tension between achieving quality software engineering and achieving the best-performing software. Sometimes one of these goals is achieved at the expense of the other. For all but the most performance-intensive situations, apply the following rule of thumb: First, make your code simple and correct; then make it fast and small, but only if necessary.