当前位置: C语言 -- 基础 -- 语句和块

语句和块(五)

八、跳转语句

跳转语句(jump statements)会导致程序执行无条件跳转至另一位置。C语言中跳转语句包括:goto语句、continue语句、break语句、return语句。


1、goto语句

goto语句具有以下语法格式:

goto identifier;

其中identifier是标识符,即标签名;gotoC语言关键词。


goto语句会导致程序执行无条件地跳转至同一函数内由指定标签名标记的语句。

int i = 0;

here :	
    i++;

if(i<3)
    goto here;

goto语句不能从具有可变修改类型标识符的作用域外跳转至该标识符的作用域内;任何跳过具有可变修改类型对象声明的goto语句都不符合ISO标准;但在该标识符作用域内的跳转是有效的。

goto label1;  //合法。
...
goto label2;  //非法,从可变修改类型对象作用域外跳入作用域内。
...
{
  label1 :
  ...
   
  goto label1;  //合法。
  ...
  goto label2;  //非法,从可变修改类型对象作用域外跳入作用域内。
  ...
  int arr[n];

  label2 :
  ...
  
  goto label1;  //合法。
  ...
  goto label2;  //合法。
  ...
}
goto label1;  //合法。
...
goto label2;  //非法,从可变修改类型对象作用域外跳入作用域内。
...

2、continue语句

continue语句具有以下语法格式:

continue;

其中continueC语言关键词。


continue语句只能用于循环体,导致程序执行跳转至最内层循环体的末尾。


对于while语句

while(...)
{
  ...
  continue; //continue语句相当于goto contin;。
  ...
  contin :
    ;
}

对于do语句

do
{
  ...
  continue; //continue语句相当于goto contin;。
  ...
  contin :
    ;
}while(...);

对于for语句

for(...)
{
  ...
  continue; //continue语句相当于goto contin;。
  ...
  contin :
    ;
}

对于嵌套的迭代语句

for(...)
{
  for(...)
  {
    ...
    continue; //continue语句相当于goto inner;。
    ...
    inner :
      ;
  }
  ...
  continue; //continue语句相当于goto outer;。
  ...
  outer :
    ;
}