C switch case 中的多个标签值 [英] multiple label value in C switch case

查看:56
本文介绍了C switch case 中的多个标签值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 Dennis M Ritchie 的书 ANSI C 的摘录:

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.

推荐答案

这是我在检查选项的程序中找到的示例:

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;
}

这可能不是我编写代码的方式(a) 但它肯定是有效的.当使用 case 导致代码比长组 || 连词更短时,通常会使用它来满足需要基本相似操作的条件:

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' || ...

<小时>

而且,事实上,K&R 本身就有一个例子,就在你提到的引用之后.它在计算不同字符类的代码中:


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) 我可能会做一些类似的事情:


(a) I probably would have done something along the lines of:

optionsOk = (strchr("aAfFqQzZX", optionChar) != NULL);

这篇关于C switch case 中的多个标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆