break
and continue
StatementsIn addition to selection and iteration statements, C# provides statements break
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
to terminate any iteration statement.
break
StatementThe break
statement, when executed in a while
, for
, do
…while
, switch
, or foreach
, causes immediate exit from the loop or switch
. Execution continues with the first statement after the control statement. Figure 6.13 demonstrates a break
statement exiting a for
. When the if
nested at line 13 in the for
statement (lines 11–19) determines that count
is 5
, the break
statement at line 15 executes. This terminates the for
statement, and the app proceeds to line 21 (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 because of the break
.
continue
StatementThe continue
statement, when executed in a while
, for
, do
…while
, or foreach
, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In while
and do
…while
statements, the app evaluates the loop-continuation test immediately after the continue
statement executes. In a for
statement, the increment expression normally executes next, then the app evaluates the loop-continuation test.
Figure 6.14 uses the continue
statement in a for
to skip the statement at line 16 when the nested if
(line 11) determines that the value of count
is 5
. When the continue
statement executes, program control continues with the increment of the control variable in the for
statement (line 9).
Some programmers feel that break
and continue
statements violate structured programming. Since the same effects are achievable with structured-programming techniques, these programmers prefer not to use break
or continue
statements.
There’s a tension between achieving quality software engineering and achieving the best-performing software. Often, one of these goals is achieved at the expense of the other. For all but the most performance-intensive situations, apply the following rule: First, make your code simple and correct; then make it fast, but only if necessary. Software Engineering Observation 6.2