C Switch
Switch 语句
与编写一堆 if..else
语句相比,您可以使用 switch
语句。
The switch
statement selects one of many code blocks to be executed
语法
switch (expression) {
case x
// 代码块
break;
case y
// 代码块
break;
default
// 代码块
}
工作原理如下
- switch 表达式只计算一次
- 表达式的值与每个 case 的值进行比较
- 如果匹配成功,则执行关联的代码块
- The
break
statement breaks out of the switch block and stops the execution - The
default
statement is optional, and specifies some code to run if there is no case match
下面的示例使用工作日数字来计算工作日名称。
示例
int day = 4;
switch (day) {
case 1
printf("Monday");
break;
case 2
printf("Tuesday");
break;
case 3
printf("Wednesday");
break;
case 4
printf("Thursday");
break;
case 5
printf("Friday");
break;
case 6
printf("Saturday");
break;
case 7
printf("Sunday");
break;
}
// 输出“星期四”(第 4 天)
自己动手试一试 »
break 关键字
When C reaches a break
keyword, it breaks out of the switch block.
这将停止块内更多代码和 case 测试的执行。
当找到匹配项并完成任务时,就该中断了。无需再进行测试。
break 可以节省大量执行时间,因为它“忽略”了 switch 块中所有其余代码的执行。
default 关键字
default
关键字指定了在没有 case 匹配时运行的一些代码。
示例
int day = 4;
switch (day) {
case 6
printf("Today is Saturday");
break;
case 7
printf("Today is Sunday");
break;
default
printf("Looking forward to the Weekend");
}
// 输出 "Looking forward to the Weekend"
自己动手试一试 »
Note: The default keyword must be used as the last statement in the switch, and it does not need a break.