目录
Switch可以用break和goto跳过剩下语句直接结束switch
一个switch语句可以有0个到多个case语句
Switch只能有0个到1个的default语句
Switch语法格式为:
switch (常量表达式/参数)
{
case (常量表达式1):
(执行语句);
case (常量表达式2):
(执行语句);
default:
(执行语句);
}
Switch需要传入参数类型可以是:(括号内为转化为常量的形式)
- 整数
- 字符(ackll值)
- 枚举类型(默认第一个枚举常量为0,依次往下++1)
- 解析为这些类型之一的标识符(即用typedef定义的前三种
switch执行流程是从上往下
如果case中的常量表达式和switch转化后的常量表达式相等(下文称为匹配)则从当前case后面进入语句执行
例:switch传入2,程序则从case 2往下执行
#include <stdio.h>
int main()
{
int a = 2;
switch (a)
{
case 1:
printf("a\n");
case 2:
printf("b\n");
case 3:
printf("c\n");
}
return 0;
}
case用法
case中的值仅用于第一次判断进入语句的入口
就像给switch中每段代码做了个标记,从标记位置往下执行代码
例:找到入口进入后,同层的case,default失去意义不执行,但其包含的语句会执行
#include <stdio.h>
int main()
{
int a = 2;
switch (a)
{
case 2:
printf("b\n");
case 1:
printf("a\n");
case 3:
printf("c\n");
}
return 0;
}
default用法:
当所有的case都不与switch匹配后,如果有default语句,就从default中进入
#include <stdio.h>
int main()
{
int a = 10;
switch (a)
{
case 1:
printf("a\n");
case 2:
printf("b\n");
case 3:
printf("c\n");
default:
printf("default\n");
}
return 0;
}
default可以与switch中传入的参数的任意值匹配,但是优先级不如case
总的来说:case能匹配就不匹配default
例:
#include <stdio.h>
int main()
{
int a = 1;
switch (a)
{
default:
printf("default\n");
case 1:
printf("a\n");
case 2:
printf("b\n");
case 3:
printf("c\n");
}
return 0;
}
Switch可以用break和goto跳过剩下语句直接结束switch
1.使用break (break可以有0个或多个)
例:
#include <stdio.h>
int main()
{
int a = 1;
switch (a)
{
case 1:
printf("a\n");
case 2:
printf("b\n");
break; //执行到此break结束switch
case 3:
printf("c\n");
default:
printf("default\n");
}
return 0;
}
2.使用goto
例:
#include <stdio.h>
int main()
{
int a = 1;
switch (a)
{
case 1:
printf("a\n");
case 2:
printf("b\n");
goto down; //跳到down的位置执行程序
case 3:
printf("c\n");
default:
printf("default\n");
}
down: //从此往下执行
return 0;
}
Switch支持嵌套
例:
#include <stdio.h>
int main()
{
int a = 1;
switch (a)
{
case 1:
printf("a\n");
switch (a)
{
case 1:
printf("嵌套");
}
}
return 0;
}
在嵌套中使用break仅仅跳出当前switch语句
例:
#include <stdio.h>
int main()
{
int a = 1;
switch (a)
{
case 1:
printf("a\n");
switch (a)
{
case 1:
printf("嵌套\n");
break;
}
case 2:
printf("b\n");
}
return 0;
}