Share via


標記陳述式

標籤可用來將程式控制權直接轉移給指定的陳述式。

語法

labeled-statement
identifier : statement
case constant-expression : statement
default : statement

標籤的範圍是宣告標籤的整個函式。

備註

標記陳述式可分三種類型。 全部都使用冒號 ( : ) 將某種類型的標籤與 語句分開。 和 defaultcase 標是 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 標。 下列程式碼片段說明語句和 identifier 標籤的使用 goto

標籤本身無法出現,但必須一律附加至 語句。 如果需要單獨使用標籤,請在標籤之後放置一個 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;
}

另請參閱

C++ 語句概觀
switch statement (C++)