Menu
CoddyTech

switch와 열거형 사례

Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 9번째.

전통적인 switch 폴스루는 두 언어 모두에 있습니다. C17은 C++의 범위 지정 enum 구문이나 클래스 기반 패턴을 지원하지 않으므로, 이 대상에서는 정수형 case와 명시적인 종료를 사용하세요.

switch는 정수형 case를 선택합니다. 의도치 않은 폴스루를 방지하려면 break를 사용하고, 일치하는 값이 없을 때는 default를 사용하세요.

C++ 예제

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>

int main(){
int code=2;switch(code){case 1:std::cout<<"new\n";break;case 2:std::cout<<"paid\n";break;default:std::cout<<"unknown\n";}
}

C++ 출력:

paid

C 예제

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
int code=2;switch(code){case 1:puts("new");break;case 2:puts("paid");break;default:puts("unknown");}
return 0;
}

C 출력:

paid
challenge icon

챌린지

쉬움

코드 1에는 new를, 2에는 paid를, 그 외의 정수에는 unknown을 반환하세요. 빌려온 상수 텍스트를 반환하세요. 호출자는 이를 해제하면 안 됩니다.

잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 main.c에서 함수를 직접 호출하므로, 선언된 공개 API와 호환되도록 유지하세요. 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한, 모든 숫자 작업 픽스처는 오버플로를 피할 만큼 작습니다. 지정된 출력만 출력하세요. 드라이버가 표시된 경우 입력 파싱과 출력을 제공합니다.

직접 해보기

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n;if(scanf("%d",&n)!=1)return 1;puts(status_name(n));return 0;}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 C의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러