C언어 switch case문에서 범위 조건 사용.
총 3가지의 방법이 있다.
*모든 예시는 0~5와, 6~10을 구분하는 예시이다.
1. gcc extension의 ... 사용.
C언어 standard문법은 아니지만,
gcc extention에서는 가능하다.
Case Ranges - Using the GNU Compiler Collection (GCC)
Case Ranges - Using the GNU Compiler Collection (GCC)
You can specify a range of consecutive values in a single case label, like this: This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive. Be careful: Write spaces around the ..., for o
gcc.gnu.org
반드시 ... 앞뒤에 공백을 붙여야한다.
#include<stdio.h>
void main(){
int a;
scanf("%d", &a);
switch(a){
case 1 ... 5:
printf("1~5\n");
break;
case 6 ... 10:
printf("6~10\n");
break;
}
}
VS에서는 에러난다.
2. 하나하나 지정해주기
정석적인 방법은 하나하나 지정해주는 것이다.
#include<stdio.h>
void main(){
int a;
scanf("%d", &a);
switch(a){
case 1:
case 2:
case 3:
case 4:
case 5:
printf("1~5\n");
break;
case 6:
case 7:
case 8:
case 9:
case 10:
printf("6~10\n");
break;
}
}
3. 몫과 나머지 이용하기
이외에, 몫과 나머지를 활용하는 방법이 있다. (구분하려는 범위들의 간격이 일정한 경우 사용할 수 있다.)
#include<stdio.h>
void main(){
int a;
scanf("%d", &a);
switch(a/5 - !(a%5)){
case 0:
printf("1~5\n");
break;
case 1:
printf("6~10\n");
break;
}
}
<참고>
Are triple dots inside a case (case '0' ... '9':) valid C language switch syntax? - Stack Overflow
Are triple dots inside a case (case '0' ... '9':) valid C language switch syntax?
I noticed this in open source code files for DRBD software (user/drbdtool_common.c) const char* shell_escape(const char* s) { /* ugly static buffer. so what. */ static char buffer[1024];
stackoverflow.com
How can I use ranges in a switch case statement in C? - Stack Overflow
How can I use ranges in a switch case statement in C?
My logic is: if number is between 1 to 10, execute first case statement if number is from 20 to 30, execute second case statement is there a solution other than the one below? case '1' ... '10':
stackoverflow.com
switch statement - Syntax for case range in C? - Stack Overflow
Syntax for case range in C?
I want to make a switch statement for in my code whose cases go over a wide span of integers (1-15000) split into 3 sections: 1-5000,5001-10000,10001-15000. I tried it once like this: switch(numb...
stackoverflow.com