是否使用if(0)跳过应该起作用的开关中的情况? [英] Is using if (0) to skip a case in a switch supposed to work?

查看:204
本文介绍了是否使用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('\n');
    }
    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 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:通常,作为开关主题的子语句是复合语句,而case和默认标签则出现在(compound)子语句包含的顶级语句中,但这不是必需的.声明可以出现在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语句的规则继续进行,而与中间的大小写标签无关.

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天全站免登陆