问题
Following is the excerpt from Dennis M Ritchie's book, ANSI C:
Each case is labeled by one or more integer-valued constants or constant expressions.
I could not come up with an example of a switch case where we have case with more than one label.
Any example illustrating the above property will be helpful.
回答1:
Here's an example I found in a program which checks options:
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;
}
It's probably not how I would have written the code(a) but it's certainly valid. It's often used when the use of case
results in shorter code than a long seties of ||
conjunctions for conditions that need substantially similar actions:
if (optionChar == 'a' || optionChar == 'A' || ...
And, in fact, K&R itself has an example, right after the quote you mention. It's in the code for counting different character classes:
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) I probably would have done something along the lines of:
optionsOk = (strchr("aAfFqQzZX", optionChar) != NULL);
回答2:
The gcc
compiler has an extension for multiple values in a single case
clause, such as:
case 1 ... 8:
However, it does not conform to the C standard.
回答3:
The accepted answer is correct for C++ too. Stroustup's book Programming Principles says the same.
You can use several case labels for a single case. Often you want the same action for a set of values in a switch. It would be tedious to repeat the action so you can label a single action by a set of case labels. For example:
He has given the following example:
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;
}
}
来源:https://stackoverflow.com/questions/51796397/multiple-label-value-in-c-switch-case