The break statement, when executed in a while
, for
, do
...while
or switch
statement, causes immediate exit from that statement. Program execution continues with the next statement. Common uses of the break
statement are to escape early from a loop or to skip the remainder of a switch
statement. Figure 5.13 demonstrates the break
statement (line 13) exiting a for
repetition statement.
1 // Fig. 5.13: fig05_13.cpp
2 // break statement exiting a for statement.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 unsigned int count; // control variable also used after loop terminates
9
10 for ( count = 1; count <= 10; ++count ) // loop 10 times
11 {
12 if ( count == 5 )
13 break; // break loop only if count is 5
14
15 cout << count << " ";
16 } // end for
17
18 cout << "
Broke out of loop at count = " << count << endl;
19 } // end main
1 2 3 4
Broke out of loop at count = 5
When the if
statement detects that count
is 5
, the break
statement executes. This terminates the for
statement, and the program proceeds to line 18 (immediately after the for
statement), which displays a message indicating the control variable value that terminated the loop. The for
statement fully executes its body only four times instead of 10. The control variable count
is defined outside the for
statement header, so that we can use the control variable both in the loop’s body and after the loop completes its execution.