跳转语句

break 语句

break 语句用于结束最近的 while、do while、for 或 switch 语句,并将程序的执行权传递给紧接在被终止语句之后的语句。

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

break 终止了 while 循环。执行权交给紧跟在 while 语句后面的if 语句,程序继续执行。

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

#1 标记的 break 终止了连字符('-')case 标号内的 for 循环,但并没有终止外层的 switch 语句,而且事实上也并没有结束当前 case 语句的执行。接着程序继续执行 for 语句后面的第一个语句,即处理连字符 case 标号下的其他代码,或者执行结束这个 case 的 break 语句。

#2 标记的 break 终止了处理连字符情况的 switch 语句,但没有终止while 循环。程序接着执行 break 后面的语句,即求解 while 的循环条件,从标准输入读入下一个 string 对象。

continue 语句

continue 语句导致最近的循环语句的当次迭代提前结束。对于 while 和do while 语句,继续求解循环条件。而对于 for 循环,程序流程接着求解 for语句头中的 expression 表达式。

例如,下面的循环每次从标准输入中读入一个单词,只有以下划线开头的单词才做处理。如果是其他的值,终止当前循环,接着读取下一个单词:

string inBuf;
while (cin >> inBuf && !inBuf.empty()) {
if (inBuf[0] != '_')
continue; // get another input
// still here? process string ...
}

continue 语句只能出现在 for、while 或者 do while 循环中,包括嵌套在这些循环内部的块语句中。

goto 语句

goto 语句提供了函数内部的无条件跳转,实现从 goto 语句跳转到同一函数内某个带标号的语句。

goto 语句使跟踪程序控制流程变得很困难,并且使程序难以理解,也难以修改。所有使用 goto 的程序都可以改写为不用 goto 语句,因此也就没有必要使用 goto 语句了。

goto 语句的语法规则如下:

goto label;

其中 label 是用于标识带标号的语句的标识符。在任何语句前提供一个标识符和冒号,即得带标号的语句:

end: return; // labeled statement, may be target of a goto

形成标号的标识符只能用作 goto 的目标。因为这个原因,标号标识符可以与变量名以及程序里的其他标识符一样,不与别的标识符重名。goto 语句和获得所转移的控制权的带标号的语句必须位于于同一个函数内。

goto 语句不能跨越变量的定义语句向前跳转:

// ...
goto end;
int ix = 10; // error: goto bypasses declaration statement
end:
// error: code here could use ix but the goto bypassed its declaration
ix = 42;

向后跳过已经执行的变量定义语句则是合法的。向后跳回到一个变量定义之前,则会使系统撤销这个变量,然后再重新创建它:

// backward jump over declaration statement ok
begin:
int sz = get_size();
if (sz <= 0) {
goto begin;
}

注意:执行 goto 语句时,首先撤销变量 sz,然后程序的控制流程跳转到带 begin: 标号的语句继续执行,再次重新创建和初始化 sz 变量。 

posted @ 2018-04-30 14:16  刘-皇叔  阅读(502)  评论(0)    收藏  举报