switch 구문은 단일 표현식을 평가하고 일치하는 case 레이블로 프로그램 흐름을 보냅니다. 일치하는 것이 없으면 선택적 default 블록이 실행됩니다. 이 의사 결정 도구는 메뉴 옵션, 오류 코드, 사용자 선택 같은 이산적인 상수 값을 처리할 때 특히 유용합니다.
각 case는 상수 표현식으로 고유하게 식별됩니다. 표현식 값이 case 레이블과 일치하면 해당 문장 블록이 실행되고, break가 생략되지 않는 한 switch를 빠져나갑니다(생략 시 fall-through 발생).
Switch-Case 문법
switch (expression) {
case constant1:
// 문장들
break;
case constant2:
// 문장들
break;
// …
default:
// 문장들
break;
}
// switch 이후 문장들
expression은 정수 또는 열거형 타입으로 평가되어야 함
Case 레이블은 상수 값; 중복은 모호성 유발하므로 피해야 함
각 case는 콜론으로 끝나고 코드 블록이 따름
break로 case 종료; 없으면 후속 case로 실행 계속 (fall-through)
default 블록은 선택 사항이며 어떤 case와도 일치하지 않을 때만 실행
Switch 문 작동 원리
다음 흐름도는 switch 문의 의사 결정 과정을 보여줍니다:
예제 1: 기본 Switch
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}
출력:
Value is 8
예제 2: Default 사용
#include <stdio.h>
int main() {
int language = 10;
switch (language) {
case 1:
printf("C#\n");
break;
case 2:
printf("C\n");
break;
case 3:
printf("C++\n");
break;
default:
printf("Other programming language\n");
}
return 0;
}
출력:
Other programming language
예제 3: Case 결합
#include <stdio.h>
int main() {
int number = 5;
switch (number) {
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
return 0;
}
출력:
Four, Five, or Six.
중첩 Switch(Nested Switches)
Switch는 중첩 가능하여 계층적 의사 결정을 허용합니다. 다음 예제는 간단한 인증 흐름을 보여줍니다:
#include <stdio.h>
int main() {
int ID, password;
printf("Please Enter Your ID:\n");
scanf("%d", &ID);
switch (ID) {
case 500:
printf("Enter your password:\n");
scanf("%d", &password);
switch (password) {
case 0:
printf("Welcome Dear Programmer\n");
break;
default:
printf("Incorrect password\n");
}
break;
default:
printf("Incorrect ID\n");
}
return 0;
}
출력:
Please Enter Your ID:
500
Enter your password:
000
Welcome Dear Programmer
장황한 If-Else보다 Switch가 나은 이유
if-else 체인으로도 같은 로직을 구현할 수 있지만, 옵션이 늘어나면 다루기 까다로워집니다. Switch 문은 더 명확한 문법, 더 나은 가독성을 제공하며, 컴파일러가 상수 표현식에 대해 점프 테이블로 최적화할 수 있습니다.