Switch와 열거형 사례
Coddy의 Ruby 개발자를 위한 C 코스 레슨. 48개 중 9번째.
Ruby의 case/when은 정확히 하나의 분기만 실행하고, 다음 분기로 이어서 실행되지 않으며, 범위나 클래스를 일치시킬 수 있습니다. C의 switch는 정수 상수 case 레이블로 이동하며, break 또는 return으로 제어 흐름을 빠져나가지 않으면 다음 case까지 계속 실행됩니다. 인식할 수 없는 정수 코드에 대비해 default를 두세요. 나중에 enum을 사용하면 이 코드에 읽기 쉬운 이름을 붙일 수 있습니다.
Ruby
code = 2
label = case code
when 1 then "new"
when 2 then "paid"
else "unknown"
end
puts labelC17
#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;
}
코드 포팅 규칙
다음 case로 이어서 실행할 필요가 없다면 switch case를 명시적으로 끝내세요.
챌린지
쉬움코드 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;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러