goto 陳述式 (C++)
語句會 goto
無條件地將控制權傳送至指定識別碼所標記的語句。
語法
goto identifier;
備註
identifier
所指定之標記的陳述式必須位於目前的函式。 所有 identifier
名稱是內部命名空間的成員,因此不會干擾其他識別項。
語句標籤只對 goto
語句有意義,否則會忽略語句標籤。 標籤不能重新宣告。
goto
不允許語句將控制權傳送至略過該位置範圍內之任何變數的初始化位置。 下列範例會引發 C2362:
int goto_fn(bool b)
{
if (!b)
{
goto exit; // C2362
}
else
{ /*...*/ }
int error_code = 42;
exit:
return error_code;
}
最好盡可能使用 break
、 continue
和 return
語句, goto
而不是 語句。 不過,因為 break
語句只會從迴圈的一個層級結束,所以您可能必須使用 goto
語句來結束深度巢狀迴圈。
如需標籤和 goto
語句的詳細資訊,請參閱 Labeled 語句 。
範例
在此範例中, goto
語句會將控制項傳送至等於 3 時 i
加上標籤 stop
的點。
// goto_statement.cpp
#include <stdio.h>
int main()
{
int i, j;
for ( i = 0; i < 10; i++ )
{
printf_s( "Outer loop executing. i = %d\n", i );
for ( j = 0; j < 2; j++ )
{
printf_s( " Inner loop executing. j = %d\n", j );
if ( i == 3 )
goto stop;
}
}
// This message does not print:
printf_s( "Loop exited. i = %d\n", i );
stop:
printf_s( "Jumped to stop. i = %d\n", i );
}
Outer loop executing. i = 0
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 1
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 2
Inner loop executing. j = 0
Inner loop executing. j = 1
Outer loop executing. i = 3
Inner loop executing. j = 0
Jumped to stop. i = 3
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應