• 검색 결과가 없습니다.

C에서는 switch 문을 사용하여 이 문제점을 해결한다

N/A
N/A
Protected

Academic year: 2022

Share "C에서는 switch 문을 사용하여 이 문제점을 해결한다"

Copied!
3
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

주 9

문 switch

□ if 문이 둘 중 하나를 택할 경우에는 이점이 있지만 여러 가지 중 하나를 택할 경우에는 복잡하게 된다, . C에서는 switch 문을 사용하여 이 문제점을 해결한다.

문은 다중 선택 문장이다 는 프로그램의 여러 가지 가능한 실행 경로 중에서 하나를 선택하는데 사용되며 다음과 같이 수행된다

switch . switch .

하나의 변수(variable)가 정수나 문자 상수(constant)들과 비교된다 만일 일치하는 것을 찾으면 일치되는 것과 관련된 문장을 수행한다. , . switch 문의 일 반적인 형식은 다음과 같다.

switch(variable) { case constant1:

statement sequence break;

case constant2:

statement sequence break;

case constant3:

statemenet sequence break;

. . default:

statement sequence break;

}

□ 여기서 default 문은 일치되는 것이 없을 때 수행되며 생략가능하다 일치되는 문장이 없고 . default 문 역시 없으면 아무 것도 수행하지 않는다. 일치하는 것을 찾으면 해당 , case와 관련된 문장들은 break를 만나거나 혹은, default 나 마지막 case의 경우에 switch 문의 끝을 만날 때까지 실행된 다.

(2)

□ 아주 간단한 예로서 다음 프로그램 , 1,2,3,4를 인식할 수 있으며 입력한 수의 영문 이름을 출력한다 즉 를 입력하면 이 프로그램은 . , 2 , two를 출력한 다.

#include "stdio.h"

main() {

int i;

printf("Enter a number between 1 and 4: ");

scanf("%d", &i);

switch(i) { case 1:

printf("one");

break;

case 2:

printf("two");

break;

case 3:

printf("three");

break;

case 4:

printf("four");

break;

default:

printf("unrecognized number");

} }

문은 문과 다른데 문의 조건식에 어떤 형태의 식이라도 올 수 있지만 문은 오직 일치하는 것만을 검사한다 또한 문에는

switch if , if switch . switch int

나 char 형만 사용할 수 있다 예를 들어 실수는 사용할 수 없다. , .

□ case 와 연관된 문장들은 블록이 아니므로 중괄호를 붙이지 않는다.

(3)

□ ANSI C 표준에서는 적어도 257개의 case 문을 허용한다 실제로 사용자는 효율성을 고려하여 훨씬 적은 수의 . case 문을 사용한다 또한 하나의 . 문에 두 개 이상의 상수가 같은 값이 될 수 없다

switch case .

□ switch 문장 안에 또 다른 하나의 switch 문장이 올 수 있다 이것을 중첩된 . switch 문이라 한다 내부와 외부 . switch 문의 case 상수가 같더라도 문 제가 되지 않는다 예를 들어 다음의 코드 단락은 전혀 문제가 되지 않는다. , .

switch(a) { case 1:

switch(b){

case 0: printf("b is false");

case 1: printf("b is true");

} break;

case2:

.

표준에서는 적어도 단계의 중첩된 문을 허용한다

ANSI C 15 switch .

참조

관련 문서

7 INPUT Input terminals to banana plugs of the furnished cords 8 FREQUENCY 4-digit decade switch for establishing the reference frequency 9 PRESET 8-digit decade switch

The other is J6 on the analog board (for battery). The box 118 is battery charger board. SW4 is power switch. The power switch SW4 does not function in this case. SW4 can be used

[r]

auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void.. default

const extern register switch continue float return typedef default for short union... – 잘못된 식별자는 컴파일

이제 switch, case문을 사용해보자.. 우리도

그러나 switch문에서의 break는 switch 문의

소형 직류 레귤레이터의 유형 - linear-mode regulator(LMPS) - switch-mode regulator(SMPS) - resonant-mode regulator(RMPS). 소형