레이블 문

레이블은 프로그램 제어를 지정된 문에 직접 전송하는 데 사용됩니다.

구문

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

레이블의 범위는 선언된 전체 함수입니다.

설명

세 가지 형식의 레이블 문이 있습니다. 모두 콜론(:)을 사용하여 문과 일부 형식의 레이블을 구분합니다. 및 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 전송할 수 있습니다. 다음 코드 조각에서는 문 및 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 문의 레이블

키워드(keyword) 이후에 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++)