JUST GO
[C] 제어문(switch문) 본문
switch문
- 정수식의 값에 따라서 여러 가지 경우 중 하나로 분기한다.


switch를 이용한 텍스트 기반의 메뉴 처리
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int menu;
char filename[32] = "test.avi";
printf("1.파일 열기\n");
printf("2.재생\n");
printf("3.재생 옵션\n");
printf("선택: ");
scanf("%d", &menu);
switch (menu) {
case 1:
printf("재생할 파일 이름? ");
scanf("%s", filename);
break;
case 2:
printf("%s를 재생합니다.\n", filename);
break;
case 3:
printf("재생 옵션을 선택합니다.\n");
break;
default:
printf("잘못 선택하셨습니다/\n");
break;
}
return 0;
}
switch를 이용한 사칙연산 계산기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int a, b;
char op;
printf("수식? ");
scanf("%d %c %d", &a, &op, &b);
switch (op) {
case '+':
printf("%d + %d = %d\n", a, b, a + b);
break;
case '-':
printf("%d - %d = %d\n", a, b, a - b);
break;
case '*':
printf("%d * %d = %d\n", a, b, a * b);
break;
case '/':
if (b != 0)
printf("%d / %d = %.2f\n", a, b, (double)a / b);
else
printf("0으로 나눌 수 없습니다.\n");
break;
default:
printf("잘못된 수식입니다.\n");
break;
}
return 0;
}
else if VS switch



switch 사용 시 주의 사항
- switch문에서 break는 생략할 수 있다.
- 실수로 break를 빠뜨리면, break를 만나거나 switch의 끝을 만날 때까지 나타나는 모든 문장들을 수행한다.

- default도 생략할 수 있다.
- switch문에 일치하는 case가 없고 default도 없으면, 아무것도 수행하지 않고 switch문을 빠져나간다.
- default의 위치
- default는 switch문 안에 어떤 위치에서도 사용될 수 있다.
- 보통은 switch문의 맨 마지막에 작성한다.
- default에도 break를 써주는 것이 좋다.

- switch의 ( ) 안에는 정수식만 사용할 수 있으며, 실수나 문자열은 사용할 수 없다.

- 특정 case에서만 사용되는 변수를 선언하려면 { }를 쓰고 그 안에 변수 선언 및 필요한 문장을 적어준다.

'C > 학습내용' 카테고리의 다른 글
[C] 반복문(2) (1) | 2022.10.05 |
---|---|
[C] 반복문 (1) | 2022.10.05 |
[C] 제어문(if문) (0) | 2022.10.05 |
[C] 연산자(3) (1) | 2022.10.05 |
[C] 연산자(2) (1) | 2022.10.05 |