multiple label value in C switch case

一个人想着一个人 提交于 2020-08-05 08:32:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!