6.10. The break Statement6.10. break 语句A 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: break 语句用于结束最近的 while、do while、for 或 switch 语句,并将程序的执行权传递给紧接在被终止语句之后的语句。例如,下面的循环在 vector 中搜索某个特殊值的第一次出现。一旦找到,则退出循环: 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. 本例中,break 终止了 while 循环。执行权交给紧跟在 while 语句后面的 if 语句,程序继续执行。 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: break 只能出现在循环或 switch 结构中,或者出现在嵌套于循环或 switch 结构中的语句里。对于 if 语句,只有当它嵌套在 switch 或循环里面时,才能使用 break。break 出现在循环外或者 switch 外将会导致编译时错误。当 break 出现在嵌套的 switch 或者循环语句中时,将会终止里层的 switch 或循环语句,而外层的 switch 或者循环不受影响: 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. #1 标记的 break 终止了连字符('-')case 标号内的 for 循环,但并没有终止外层的 switch 语句,而且事实上也并没有结束当前 case 语句的执行。接着程序继续执行 for 语句后面的第一个语句,即处理连字符 case 标号下的其他代码,或者执行结束这个 case 的 break 语句。 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. #2 标记的 break 终止了处理连字符情况的 switch 语句,但没有终止 while 循环。程序接着执行 break 后面的语句,即求解 while 的循环条件,从标准输入读入下一个 string 对象。 ![]() |