if 문과 같이, switch case 는 다양한 조건에서 실행되어야 하는 다른 코드를 프로그래머가 지정하는 것을 허용하여, 프로그램의 흐름을 제어한다.
특히, switch 문은 변수 값을 case 문에 지정된 값과 비교한다. case 문이 그 값이 변수 값과 같은 것을 찾으면 해당 case 문에 있는 코드가 실행된다.
break 키워드는 switch 문을 빠져 나오고, 각 case의 끝에 전형적으로 쓰인다. break 문이 없으면, switch 문이 break 나올 때까지 (break 안 나오면 switch 문 끝날 때까지) 다음 문장을 계속 실행("falling-through")한다.
문법
switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
break;
}
매개변수
var: 다양한 case 와 비교할 변수 값. 허용되는 자료형: int, char label1, label2: 상수. 허용되는 자료형: int, char
반환
없음
예제 코드
switch (var) {
case 1:
//do something when var equals 1
break;
case 2:
//do something when var equals 2
break;
default:
// if nothing else matches, do the default
// default is optional
break;
}
더보기
Title
Arduino Newsletter
We care about the privacy and personal data of our users.
To continue, please give us your consent:
Please confirm that you have read the privacy policy
Thank you for subscribing!
Curious to learn more?
Are you also a teacher, student, or professional that loves using Arduino in your day-to-day activities?
Then keep up-to-date with either our STEM or Professional monthly newsletters.
Arduino weekly newsletter (already subscribed)
Educators can benefit from the ever growing tech that shapes our environment through fun cool projects.
Why not awe your boss with highly innovative ways to help keep your enterprise connected at no extra cost?
Arduino Survey
We'd like to get to know you little better.
Please help us improve by answering this super short optional survey.