c语言switch case能接多个常量吗?
时间: 2023-12-12 09:35:09
浏览: 345
是的,C[[语言](https://geek.csdn.net/educolumn/05c8de7581a582e6d46821757663ed30?spm=1055.2569.3001.10083)中](https://geek.csdn.net/educolumn/04987620776e6a687043deb27ae38e47?spm=1055.2569.3001.10083)的switch case语句可以接多个常量。可以使用逗号分隔多个常量,例如:
switch (num) {
case 1:
case 2:
case 3:
printf("num is 1, 2, or 3");
[break](https://geek.csdn.net/educolumn/2aa3796b1a65eda8de264fdb2ce124be?spm=1055.2569.3001.10083);
case 4:
printf("num is 4");
break;
default:
printf("num is not 1, 2, 3, or 4");
在上面的例子中,当num的值为1、2或3时,都会执行第一个case语句块中的[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)。这样可以避免在多个case语句块中重复编写相同的[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)。
相关问题
c语言switch case多个条件
在C语言中,可以使用多个条件的switch case语句。可以使用逗号分隔多个条件,如下所示:
switch (expression) {
case constant1, constant2:
// 执行语句1
break;
case constant3:
// 执行语句2
break;
default:
// 执行语句3
break;
在上面的示例中,如果表达式(expression)的值等于constant1或constant2,则执行语句1;如果表达式的值等于constant3,则执行语句2;如果表达式的值都不等于这些常量,则执行语句3。注意每个case后面都需要添加break语句,以防止执行其他case中的语句。
C语言switch一个case多个条件
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)