c语言switchcase语句例子
时间: 2023-11-11 20:56:42 浏览: 140
switch-case语句是C语言中的一种控制结构,通过判断控制表达式的值,选择不同的分支执行相应的语句块。下面是一个C语言的switch-case语句的例子:
```c
#include <stdio.h>
int main() {
int type = 2;
switch (type) {
case 1:
printf("您好!");
break;
case 2:
printf("早上好!");
break;
case 3:
printf("晚上好!");
break;
case 4:
printf("再见!");
break;
default:
printf("啊,啊什么啊?");
break;
}
return 0;
}
```
在这个例子中,我们定义了一个变量type,并将其赋值为2。根据type的值,程序会执行相应的语句块。由于type的值为2,所以程序会输出"早上好!"。
相关问题
c语言switch case语句例子
```c
switch (n) {
case 1:
printf("Case 1\n");
break;
case 2:
printf("Case 2\n");
break;
default:
printf("Default case\n");
}
```
这是一个 C 语言中 switch-case 语句的示例。在这个示例中,switch 语句的变量是 n。当 n 等于 1 时,执行 case 1 中的语句,当 n 等于 2 时,执行 case 2 中的语句。如果 n 不等于 1 也不等于 2,则执行 default 中的语句。
每个 case 后的冒号表示 case 块的开始,break 语句表示结束该 case 块并跳出 switch 语句。如果省略 break,程序会继续执行下一个 case。
c语言switch case语句break
### C语言 `switch` 语句中的 `break`
在C语言中,`switch` 是一种多分支选择结构,用于根据变量的不同取值执行不同的操作。当匹配到某个特定条件时,默认情况下程序会继续向下执行后续的case语句直到遇到 `break` 或者整个 `switch` 结束。
#### `break` 的作用
`break` 关键字用来终止当前最内层的循环体或 `switch` 语句[^1]。对于 `switch` 来说,在每个 `case` 后面加上 `break;` 可以防止代码“贯穿”(fall-through),即一旦找到匹配项并处理完毕后立即退出 `switch` 而不再检查其他情况。
如果没有设置 `break`,则即使已经找到了符合条件的情况,也会继续往下执行后面的 `case` 和默认部分的内容,这通常不是预期的行为。
#### 示例代码展示 `break` 的使用方法
下面是一个简单的例子来说明如何正确地使用 `break`:
```c
#include <stdio.h>
int main() {
char grade;
printf("Enter your grade (A, B, C): ");
scanf("%c", &grade);
switch(grade){
case 'A':
printf("Excellent!\n");
break; // 防止继续执行下一个case
case 'B':
printf("Good\n");
break;
case 'C':
printf("Need improvement\n");
break;
default:
printf("Invalid grade entered.\n");
}
return 0;
}
```
在这个例子中,如果输入的是 `'A'` ,那么只会打印 `"Excellent!"` 并结束 `switch` 块;而不会意外地也去打印后面两个消息。这是因为每次成功匹配之后都调用了 `break` 来阻止进一步的执行流程[^2]。
阅读全文
相关推荐
















