goto 語句
來自 cppreference.com
無條件地將控制權轉移到目標位置。
當無法使用傳統構造將控制權轉移到目標位置時使用。
目錄 |
[編輯] 語法
attr-spec-seq(可選) goto label ; |
|||||||||
label | - | goto 語句的目標標籤 |
屬性說明序列 | - | (C23 起)可選的屬性列表,應用於 goto 語句 |
[編輯] 解釋
goto
語句導致無條件跳轉(控制權轉移)到由指定標籤字首的語句(該標籤必須出現在與 goto 語句相同的函式中),除非此跳轉將進入變長陣列或其他可變修改型別的作用域。(C99 起)
標籤是後跟冒號(:
)和語句(C23 前)的識別符號。標籤是唯一具有函式作用域的識別符號:它們可以在其出現的同一函式中的任何地方使用(在 goto 語句中)。任何語句之前都可以有多個標籤。
允許進入非可變修改變數的作用域 goto lab1; // OK: going into the scope of a regular variable int n = 5; lab1:; // Note, n is uninitialized, as if declared by int n; // goto lab2; // Error: going into the scope of two VM types double a[n]; // a VLA int (*p)[n]; // a VM pointer lab2: 如果 { int n = 1; label:; int a[n]; // re-allocated 10 times, each with a different size if (n++ < 10) goto label; // leaving the scope of a VM } |
(C99 起) |
[編輯] 關鍵詞
[編輯] 注意
由於宣告不是語句,因此宣告前的標籤必須使用空語句(冒號後立即跟分號)。塊末尾前的標籤也適用。 |
(直至 C23) |
C++ 對 goto
語句施加了額外的限制,但允許在宣告前使用標籤(在 C++ 中宣告是語句)。
[編輯] 示例
執行此程式碼
#include <stdio.h> int main(void) { // goto can be used to leave a multi-level loop easily for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { printf("(%d;%d)\n",x,y); if (x + y >= 3) goto endloop; } } endloop:; }
輸出
(0;0) (0;1) (0;2) (1;0) (1;1) (1;2)
[編輯] 參考
- C17 標準 (ISO/IEC 9899:2018)
- 6.8.6.1 goto 語句 (p: 110-111)
- C11 標準 (ISO/IEC 9899:2011)
- 6.8.6.1 goto 語句 (p: 152-153)
- C99 標準 (ISO/IEC 9899:1999)
- 6.8.6.1 goto 語句 (p: 137-138)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 3.6.6.1 goto 語句
[編輯] 另請參閱
C++ 文件關於
goto 語句 |