switch 语句中的逗号运算符是什么意思?
这意味着你有一个旧的编译器。
编辑帖子(显示case range示例)
前两个示例(包括您的原始代码)显示了不正确的 switch 语句语法(带有解释)。第三个代码示例展示了如何正确堆叠大小写标签:
在您的代码中,编译器应该在case 1, 之后标记了第一个逗号
#include <ansi_c.h>
int main(void){
int x = 2;
switch(x)
{
case 1,2,1: printf("Case 1 is executed");
break; //error flagged at first comma, and all comma after in case
case 2,3,1: printf("Case 2 is executed");
break;
default : printf("Default case is executed");
}
return 0;
}
而且,即使这样修改,您也应该得到重复标签错误:
#include <ansi_c.h>
int main(void){
int x = 2;
switch(x)
{
case 1:
case 2:
case 1: printf("Case 1 is executed"); //duplicate label 1 error. (and others below)
break;
case 2:
case 3:
case 1: printf("Case 2 is executed");
break;
default : printf("Default case is executed");
}
return 0;
}
这个例子是完全合法的(C99, C11) 并且很有用:即没有重复的标签,并且语法通过堆叠unique标签符合正确的开关用法处理case 1: OR case 2: OR case 3: 应以相同方式处理的情况(在同一块中)。当然,案例 4、5 和 6 也是如此。
#include <ansi_c.h>
int main(void){
int x = 2;
switch(x)
{
case 1:
case 2:
case 3: printf("Case 1,2 or 3 is executed"); //duplicate label 1 error. (and others below)
break;
case 4:
case 5:
case 6: printf("Case 4,5 or 6 is executed");
break;
}
getchar();
return 0;
}
最后一个例子只是为了完整性。它说明了case range 表达式。虽然引起了 C 程序员的兴趣,但它还不是 C99 或 C11 的一部分,而是 Sun (a flavor of unix) 和 GNU C compiler 的扩展(等):
...
switch(x)
{
case 'a' ... 'z': //note: spaces between all characters ('a') and ellipses are required
printf("lowercase alpha char detected");
break;
case 'A' ... 'B':
printf("uppercase alpha char detected");
break;
default: printf("Default case is executed");
}
...
您看到从一个编译器到另一个编译器的结果模棱两可的原因可能是 Turbo C 真的真的老了。您正在使用的版本可能是针对不再适用的 C 标准版本实施的。
考虑更改为当前的编译器。 MinGW 是一种廉价(免费)的替代方案。 MinGW 是一个维护良好的开源编译器。如果您喜欢使用集成开发环境 (IDE),Code::Blocks 是一个选项,也是免费的,并且作为选项与 MinGW 捆绑在一起。
关于兼容性,请在此链接中搜索 Comparison to Other Compiler Suites 以阅读有关 MinGW 扩展的信息。 MinGW 扩展在扩展功能的同时,有时会使使用它们编写的代码与其他当前 编译器不可移植。建议在使用时谨慎使用。