是否使用 if (0) 跳过应该工作的开关中的一个案例? [英] Is using if (0) to skip a case in a switch supposed to work?

查看:25
本文介绍了是否使用 if (0) 跳过应该工作的开关中的一个案例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我希望 C++ switch 语句中的两种情况都落入第三种情况.具体来说,第二种情况会通过第三种情况,第一种情况也会通过第三种情况不通过第二种情况.

I have a situation where I would like for two cases in a C++ switch statement to both fall through to a third case. Specifically, the second case would fall through to the third case, and the first case would also fall through to the third case without passing through the second case.

我有一个愚蠢的想法,尝试了它,它成功了!我将第二种情况包装在 if (0) { ... } 中.它看起来像这样:

I had a dumb idea, tried it, and it worked! I wrapped the second case in an if (0) { ... }. It looks like this:

#ifdef __cplusplus
#  include <cstdio>
#else
#  include <stdio.h>
#endif

int main(void) {
    for (int i = 0; i < 3; i++) {
        printf("%d: ", i);
        switch (i) {
        case 0:
            putchar('a');
            // @fallthrough@
            if (0) {        // fall past all of case 1 (!)
        case 1:
            putchar('b');
            // @fallthrough@
            }
        case 2:
            putchar('c');
            break;
        }
        putchar('
');
    }
    return 0;
}

当我运行它时,我得到了想要的输出:

When I run it, I get the desired output:

0: ac
1: bc
2: c

我在 C 和 C++ 中都试过了(都用 clang),结果是一样的.

I tried it in both C and C++ (both with clang), and it did the same thing.

我的问题是:这是有效的 C/C++ 吗?它应该做它该做的事吗?

My questions are: Is this valid C/C++? Is it supposed to do what it does?

推荐答案

是的,这是允许的,它会做你想做的事.对于 switch 语句,C++ 标准 :

Yes, this is allowed, and it does what you want. For a switch statement, the C++ standard says:

case 和 default 标签本身不会改变控制流,控制流在这些标签上继续畅通无阻.要退出 switch,请参阅 break.

case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break.

[注 1:通常,作为 switch 主题的子语句是复合的,大小写和默认标签出现在(复合)子语句中包含的顶级语句上,但这不是必需的.声明可以出现在 switch 语句的子语句中.——尾注]

[Note 1: Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required. Declarations can appear in the substatement of a switch statement. — end note]

因此,当 if 语句被求值时,控制流将根据 if 语句的规则进行,而不管中间的 case 标签.

So when the if statement is evaluated, control flow proceeds according to the rules of an if statement, regardless of intervening case labels.

这篇关于是否使用 if (0) 跳过应该工作的开关中的一个案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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