6.10. The 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. For example, the following loop searches a vector for the first occurrence of a particular value. Once it's found, the loop is exited: vector<int>::iterator iter = vec.begin(); while (iter != vec.end()) { if (value == *iter) break; // ok: found it! else ++iter; // not found: keep looking }// end of while if (iter != vec.end()) // break to here ... // continue processing In this example, the break terminates the while loop. Execution resumes at the if statement immediately following the while. A break can appear only within a loop or switch statement or in a statement nested inside a loop or switch. A break may appear within an if only when the if is inside a switch or a loop. A break occurring outside a loop or switch is a compile-time error. When a break occurs inside a nested switch or loop statement, the enclosing loop or switch statement is unaffected by the termination of the inner switch or loop: string inBuf; while (cin >> inBuf && !inBuf.empty()) { switch(inBuf[0]) { case '-': // process up to the first blank for (string::size_type ix = 1; ix != inBuf.size(); ++ix) { if (inBuf[ix] == ' ') break; // #1, leaves the for loop // ... } // remaining '-' processing: break #1 transfers control here 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 within 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 the hyphen case or the break that completes that section. The break labeled #2 terminates the switch statement after handling the hyphen case but does not terminate the enclosing while loop. Processing continues after that break by executing the condition in the while, which reads the next string from the standard input. ![]() |