目录

goto statement

goto语句提供从goto到同一函数中带标签语句的无条件跳转。

NOTE - 强烈建议不要使用goto语句,因为它很难跟踪程序的控制流程,使程序难以理解且难以修改。 任何使用goto的程序都可以被重写,因此它不需要goto。

语法 (Syntax)

C ++中goto语句的语法是 -

goto label;
..
.
label: statement;

其中label是标识标签语句的标识符。 带标签的语句是任何前面带有标识符后跟冒号(:)的语句。

流程图 (Flow Diagram)

C ++ goto语句

例子 (Example)

#include <iostream>
using namespace std;
int main () {
   // Local variable declaration:
   int a = 10;
   // do loop execution
   LOOP:do {
      if( a == 15) {
         // skip the iteration.
         a = a + 1;
         goto LOOP;
      }
      cout << "value of a: " << a << endl;
      a = a + 1;
   } 
   while( a < 20 );
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

goto的一个好用途是退出深度嵌套的例程。 例如,考虑以下代码片段 -

for(...) {
   for(...) {
      while(...) {
         if(...) goto stop;
         .
         .
         .
      }
   }
}
stop:
cout << "Error in program.\n";

消除goto会强制执行许多额外的测试。 一个简单的break语句在这里不起作用,因为它只会导致程序退出最内层的循环。

↑回到顶部↑
WIKI教程 @2018