標籤可用來將程式控制權直接轉移給指定的陳述式。
語法
labeled-statement:
identifier:statement
caseconstant-expression:statement
default:statement
卷標的範圍是宣告標籤的整個函式。
備註
標記陳述式可分三種類型。 全部都使用冒號 (:) 將某種類型的標籤與語句分開。 和 case 標籤default是case語句特有的。
#include <iostream>
using namespace std;
void test_label(int x) {
if (x == 1){
goto label1;
}
goto label2;
label1:
cout << "in label1" << endl;
return;
label2:
cout << "in label2" << endl;
return;
}
int main() {
test_label(1); // in label1
test_label(2); // in label2
}
標籤和 goto 語句
來源程式中標籤的外觀 identifier 會宣告標籤。
goto只有語句可以將控件傳送至標籤identifier。 下列代碼段說明語句和goto標籤的使用identifier:
卷標本身無法出現,但必須一律附加至 語句。 如果需要單獨使用標籤,請在標籤之後放置一個 null 陳述式。
卷標具有函式範圍,且無法在函式中重新宣告。 然而,在不同的函式中可以使用相同名稱做為標籤。
// labels_with_goto.cpp
// compile with: /EHsc
#include <iostream>
int main() {
using namespace std;
goto Test2;
cout << "testing" << endl;
Test2:
cerr << "At Test2 label." << endl;
}
//Output: At Test2 label.
語句中的標籤case
在關鍵詞之後 case 出現的標籤也無法出現在語句之外 switch 。 (此限制也適用於 default 關鍵詞。下列代碼段顯示標籤的正確用法 case :
// Sample Microsoft Windows message processing loop.
switch( msg )
{
case WM_TIMER: // Process timer event.
SetClassWord( hWnd, GCW_HICON, ahIcon[nIcon++] );
ShowWindow( hWnd, SW_SHOWNA );
nIcon %= 14;
Yield();
break;
case WM_PAINT:
memset( &ps, 0x00, sizeof(PAINTSTRUCT) );
hDC = BeginPaint( hWnd, &ps );
EndPaint( hWnd, &ps );
break;
case WM_CLOSE:
KillTimer( hWnd, TIMER1 );
DestroyWindow( hWnd );
if ( hWnd == hWndMain )
PostQuitMessage( 0 ); // Quit the application.
break;
default:
// This choice is taken for all messages not specifically
// covered by a case statement.
return DefWindowProc( hWnd, Message, wParam, lParam );
break;
}