[C++/컴파일 에러] error: cannot jump from switch statement to this case label 에러 해결 및 원인

2024. 7. 23. 18:00·💻 Programming/C++

 

❓ switch-case문의 각 case블록을 { }으로 감싸는 것은 선택 사항이었던 게 아니었나? 

 

되돌아보니, 한 번도 case문은 왜 블록처리를 안 하는지 의문을 품은 적이 없었다.

 

 

 

 

📌 1) 에러 발생

아래 2번째 줄에서 나타난 note: jump bypasses variable initialization

참고: 점프는 변수 초기화를 우회합니다.

 


아래 5번째 줄에서 나타난 error: cannot jump from switch statement to this case label

오류: switch 문에서 이 케이스 라벨로 이동할 수 없습니다.

 

    case 3: 
        vector<int> v;
        // 생략
        
    case 4:
    	// 생략

 

 

 

 

 

📌 2) 에러 해결

해결 방법은 매우 간단하다!

아래처럼 case문을 { } 블록으로 감싸면 해결이 된다.

    case 3: {
        vector<int> v;
        // 생략
    }
        
    case 4:
    	// 생략

 

 

 

 

 

📌 3) 에러 분석

찾아보니,

C++에서 switch-case문 내의 case 블록을 감싸는 것은 선택 사항이 맞다.

 

하지만, 특정 상황에서는 컴파일 에러가 발생할 수 있다.

 

왜냐하면, switch-case 문은 하나의 블록으로 간주되기 때문에, 각 case 블록 내에서 선언된 변수는 전체 switch 블록 내에서 유효하다. 

 

따라서, 아래 코드처럼 같은 이름의 변수를 여러 case 블록 내에서 선언하려고 하면, 변수의 중복 선언으로 인해 컴파일 에러가 발생할 것이다.

switch (value) {
    case 1:
        int x = 10; // 변수 x 선언
        break;
    case 2:
        int x = 20; // ❗ 오류: 변수 x가 이미 선언됨
        break;
}

case 1: 과 case 2: 는 다른 블록처럼 보이지만, 사실은 같은 블록 내에서 변수를 선언한 셈이다.

 

그리고 case 블록 내에서 변수를 선언하고 초기화할 때, { }로 감싸지 않으면 변수의 초기화 순서나 범위 문제로 인해 에러가 발생할 수 있다.

 

결국, 코드의 안전성과 명확성을 위해 { }를 사용하는 것이 좋은 습관이라고 할 수 있다.

 

 

 

☁ switch - case 문을 사용할 때 각 case블록을 { }로 감싸는 습관을 가지자.

 

 


 

 참고 

 

https://www.reddit.com/r/cpp_questions/comments/a0c6tp/error_jump_to_case_label/

 

From the cpp_questions community on Reddit

Explore this post and more from the cpp_questions community

www.reddit.com

 

https://stackoverflow.com/questions/34829955/what-is-causing-this-cannot-jump-from-switch-statement-to-this-case-label

 

What is causing this: Cannot jump from switch statement to this case label

This is a switch statement that I am getting errors on: switch (transaction.transactionState) { case SKPaymentTransactionStatePurchasing: // show wait view here ...

stackoverflow.com

 

저작자표시 비영리 변경금지 (새창열림)

'💻 Programming > C++' 카테고리의 다른 글

[Visual Studio Code] VS Code C++ 개발 환경 설정 (MinGW)  (0) 2024.07.27
[C++] STL(Standard Template Library) 정리  (0) 2024.07.04
[C++] STL vector 사용법  (0) 2024.07.03
'💻 Programming/C++' 카테고리의 다른 글
  • [C++] STL sort() 함수 사용법
  • [Visual Studio Code] VS Code C++ 개발 환경 설정 (MinGW)
  • [C++] STL(Standard Template Library) 정리
  • [C++] STL vector 사용법
Mojing_
Mojing_
매일 매일 경험치를 쌓는 모징이의 개발 블로그입니다 :) This is Mojing’s Dev Blog where she gain experience points every day. :)
  • Mojing_
    모징이의 개발 경험치
    Mojing_
  • 전체
    오늘
    어제
    • 분류 전체보기 (143)
      • 👻 Unity (5)
        • 🔧 기능 구현 (0)
        • 💡 유니티 팁 (0)
        • 📘 Unity 노트 (2)
      • 💻 Programming (14)
        • C (3)
        • C++ (9)
        • C# (0)
        • Swift (2)
      • 💾 Computer Science (16)
        • Algorithm (9)
        • Software Engineering (7)
      • 🐸 Problem Solving (108)
        • Programmers (41)
        • BOJ (67)
      • 🔋 ETC (0)
      • 💡 Quest Log (0)
  • 인기 글

  • 공지사항

  • 태그

    BOJ
    CS
    C++
    backtracking
    DFS/BFS
    Unity
    programmers
    algorithm
    Problem Solving
    dynamic programming
    오블완
    티스토리챌린지
    sort
    프로그래머스
    탐색
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Mojing_
[C++/컴파일 에러] error: cannot jump from switch statement to this case label 에러 해결 및 원인
상단으로

티스토리툴바