以下是摘自Dennis M Ritchie的书ANSI C:
每种情况都由一个或多个整数值常量或常量表达式标记。
我无法提出一个交换案例的例子,其中我们有带有多个标签的案例。
任何说明上述属性的示例都会有帮助。
答案 0 :(得分:4)
这是我在检查选项的程序中找到的示例:
switch (optionChar) {
case 'a': case 'A':
case 'f': case 'F':
case 'q': case 'Q':
case 'z': case 'Z': optionsOk = TRUE; break;
default: optionsOk = FALSE; break;
}
这可能不是我编写代码的方式(a),但是它肯定是有效的。在需要基本相似动作的条件下,使用case
导致代码比一组较长||
连词短时,通常会使用它:
if (optionChar == 'a' || optionChar == 'A' || ...
事实上,K&R本身有一个例子,在您引用的引号之后。。它在代码中用于计数不同的字符类:
while ((c = getchar()) != EOF) {
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
ndigit[c-'0']++;
break;
case ' ': case '\n': case '\t':
nwhite++;
break;
default:
nother++;
break;
}
}
(a)我可能会做以下事情:
optionsOk = (strchr("aAfFqQzZX", optionChar) != NULL);
答案 1 :(得分:1)
gcc
编译器在单个case
子句中具有多个值的扩展名,例如:
case 1 ... 8:
但是,它不符合C标准。
答案 2 :(得分:0)
接受的答案也适用于C ++。 Stroustup的书《 Programming Principles》也是如此。
您可以在一个案例中使用多个案例标签。通常,您希望对开关中的一组值执行相同的操作。重复该操作很繁琐,因此您可以标记单个 通过一组案例标签采取行动。例如:
他给出了以下示例:
int main() // you can label a statement with several case labels
{
cout << "Please enter a digit\n";
char a;
cin >> a;
switch (a) {
case '0': case '2': case '4': case '6': case '8':
cout << "is even\n";
break;
case '1': case '3': case '5': case '7': case '9':
cout << "is odd\n";
break;
default:
cout << "is not a digit\n";
break;
}
}