在C语言中,很多时候都会用到switch语句,不过一直没有好好研究switch的详细用法。
2:语法
- switch(表达式) {
- case 常量表达式:零条或多条语句
- default:零条或多条语句
- case 常量表达式:零条或多条语句
- }
- case后跟的是常量值或常量表达式
- default可以出现在case列表的任何位置,习惯上放在最后,在其他case均无法匹配时执行
- 如果没有default并且case均未匹配时,switch语句将什么也不做
- 标准c编译器允许有257个case标签
- case内的语句都可以被加上标签
- #include <stdio.h>
-
-
static void
-
test_switch_1(void)
-
{
-
int i = 3;
-
-
switch (i) {
-
case 1: printf("case 1\n");
-
case 2: printf("case 2\n");
-
case 3: printf("case 3\n");
-
default: printf("default\n");
-
case 4: printf("case 4\n");
-
}
-
-
switch (1+2) {
-
case 1: printf("case 1\n");
-
case 2: printf("case 2\n");
-
case 3: printf("case 3\n");
-
default: printf("default\n");
-
case 4: printf("case 4\n");
-
}
-
-
const int three = 3;
-
switch (3) {
-
case 1: printf("case 1\n");
-
case 2: printf("case 2\n");
-
case three: printf("case 3\n");
-
default: printf("default\n");
-
case 4: printf("case 4\n");
-
}
-
}
-
-
static void
-
test_switch_2(void)
-
{
-
switch (2) {
-
case 2: do_again:
-
case 3: printf("looping\n"); goto do_again;
-
default: printf("Never here");
-
}
-
}
-
-
static void
-
test_switch_3(void)
-
{
-
int i = 2;
-
switch (i) {
-
case 1: printf("case 1\n");
-
case 2: {
-
if (i > 1)
-
break;
-
}
-
case 3: printf("case 3\n");
-
default: printf("default\n");
-
}
-
}
-
-
int
-
main(int argc, char **argv)
-
{
-
// test_switch_1();
-
// test_switch_2();
-
// test_switch_3();
-
-
return 0;
- }
- xdzh@xdzh-laptop:/media/home/work/c$ gcc -Wall -O2 -o switch switch.c
-
switch.c: In function ‘test_switch_1’:
- switch.c:28: error: case label does not reduce to an integer constant
test_switch_2结果:
- xdzh@xdzh-laptop:/media/home/work/c$ ./switch
- looping
- looping
- looping
- looping
- looping
- looping
- looping
test_switch_3结果:
- xdzh@xdzh-laptop:/media/home/work/c$ ./switch
- xdzh@xdzh-laptop:/media/home/work/c$