ラベル付きステートメント

ラベルはプログラムの制御を特定のステートメントに直接移動するために使用されます。

構文

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

ラベルのスコープはラベルが宣言されている関数全体です。

解説

次の 3 種類のラベル付きステートメントがあります。 すべての種類で、そのタイプのラベルをステートメントと区切るためにコロン (:) が使用されます。 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 ラベルは、ラベルを宣言します。 identifier ラベルにコントロールを移動できるのは、goto ステートメントのみです。 次のコードでは 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キーワード (keyword).)次のコード フラグメントは、ラベルの正しい使用方法を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 ステートメント (C++)