break
StatementA break
statement terminates the nearest enclosing while
, do while
, for
, or switch
statement. Execution resumes at the statement immediately following the terminated statement.
A break
can appear only within an iteration statement or switch
statement (including inside statements or blocks nested inside such loops). A break
affects only the nearest enclosing loop or switch
:
string buf;
while (cin >> buf && !buf.empty()) {
switch(buf[0]) {
case '-':
// process up to the first blank
for (auto it = buf.begin()+1; it != buf.end(); ++it) {
if (*it == ' ')
break; // #1, leaves the for loop
// . . .
}
// break #1 transfers control here
// remaining '-' processing:
break; // #2, leaves the switch statement
case '+':
// . . .
} // end switch
// end of switch: break #2 transfers control here
} // end while
The break
labeled #1 terminates the for
loop that follows the hyphen case
label. It does not terminate the enclosing switch
statement and in fact does not even terminate the processing for the current case. Processing continues with the first statement following the for
, which might be additional code to handle a hyphen or the break
that completes that section.
The break
labeled #2 terminates the switch
but does not terminate the enclosing while
loop. Processing continues after that break
by executing the condition in the while
.
Exercise 5.20: Write a program to read a sequence of string
s from the standard input until either the same word occurs twice in succession or all the words have been read. Use a while
loop to read the text one word at a time. Use the break
statement to terminate the loop if a word occurs twice in succession. Print the word if it occurs twice in succession, or else print a message saying that no word was repeated.