C++ goto 語句



goto 語句提供從 goto 到同一函式中帶標籤語句的無條件跳轉。

注意 - 強烈建議不要使用 goto 語句,因為它使得難以跟蹤程式的控制流程,從而使程式難以理解和修改。任何使用 goto 的程式都可以重寫,使其不需要 goto。

語法

C++ 中 goto 語句的語法如下:

goto label;
..
.
label: statement;

其中 label 是一個識別符號,用於標識帶標籤的語句。帶標籤的語句是任何以識別符號後跟冒號 (:) 開頭的語句。

流程圖

C++ goto statement

示例

#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 語句在這裡不起作用,因為它只會導致程式退出最內層迴圈。

廣告