switch 语句允许我们在多个备选代码块中执行一个代码块。
你可以用 if...else..if
阶梯来实现同样的事情。然而,switch
语句的语法读写起来要容易得多。
switch...case 语法
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
switch 语句如何工作?
该 expression 被计算一次,并与每个 case 标签的值进行比较。
- 如果匹配,则执行匹配标签后的相应语句。例如,如果表达式的值等于 constant2,则执行
case constant2:
后的语句,直到遇到break
。 - 如果没有匹配项,则执行 default 语句。
注意事项
- 如果我们不使用
break
语句,匹配标签后的所有语句也将被执行。 switch
语句中的default
子句是可选的。
switch 语句流程图

示例:简易计算器
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
输出
Enter an operator (+, -, *, /): - Enter two operands: 32.5 12.4 32.5 - 12.4 = 20.1
用户输入的 - 运算符存储在 operation 变量中。并且,两个操作数 32.5 和 12.4 分别存储在变量 n1 和 n2 中。
由于 operation 是 -
,程序的控制会跳转到
printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);
最后,break 语句终止了 switch
语句。