The continue statement, when executed in a while
, for
or do
...while
statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. In while
and do
...while
statements, the loop-continuation test evaluates immediately after the continue
statement executes. In the for
statement, the increment expression executes, then the loop-continuation test evaluates.
Figure 5.14 uses the continue
statement (line 11) in a for
statement to skip the output statement (line 13) when the nested if
(lines 10–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
header (line 8) and loops five more times.
1 // Fig. 5.14: fig05_14.cpp
2 // continue statement terminating an iteration of a for statement.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 for ( unsigned int count = 1; count <= 10; ++count ) // loop 10 times
9 {
10 if ( count == 5 ) // if count is 5,
11 continue; // skip remaining code in loop
12
13 cout << count << " ";
14 } // end for
15
16 cout << "
Used continue to skip printing 5" << endl;
17 } // end main
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
In Section 5.3, we stated that the while
statement could be used in most cases to represent the for
statement. The one exception occurs when the increment expression in the while
statement follows the continue
statement. In this case, the increment does not execute before the program tests the loop-continuation condition, and the while
does not execute in the same manner as the for
.
3.21.246.223