Table of Contents
C switch 문 변수 생성
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
에러
switch 문의 경우 실행코드가 run-time 에 결정된다.
또한, switch 문은 { ...... }
블럭에 의해 변수의 범위를 공유한다.
아래와 같이 변수 생성을 case 문에서 하게되면,
아래의 코드에서는 변수가 초기화되지 않을 수도 있고,
심지어 변수가 생성되지 않을수도 있어 compiler error 가 된다.
switch(1) {
case 1: int x = 0; // initialization
std::cout << x << '\n';
break;
default: // compilation error: jump to default: would enter the scope of 'x'
// without initializing it
std::cout << "default\n";
break;
}
오류 수정
아래와 같이 { ...... }
블록을 추가로 지정해 주면 변수의 범위가 고정되어서,
위와 같은 오류가 발생하지 않는다.
switch(1) {
case 1: { int x = 0;
std::cout << x << '\n';
break;
} // scope of 'x' ends here
default: std::cout << "default\n"; // no error
break;
}