gpt4 book ai didi

c++ - 是否使用 if (0) 跳过应该工作的开关中的案例?

转载 作者:行者123 更新时间:2023-12-03 06:36:06 25 4
gpt4 key购买 nike

我有一种情况,我希望 C++ switch 语句中的两种情况都落入第三种情况。具体来说,第二种情况会落入第三种情况,而第一种情况也会落入第三种情况而不经过第二种情况。
我有一个愚蠢的想法,尝试了一下,它奏效了!我将第二个案例包裹在 if (0) { 中... } .它看起来像这样:

#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;
}
当我运行它时,我得到了所需的输出:
0: ac
1: bc
2: c
我在 C 和 C++(都用 clang)中尝试过它,它做了同样的事情。
我的问题是:这是有效的 C/C++ 吗?它应该做它所做的吗?

最佳答案

是的,这是允许的,它可以满足您的需求。对于 switch声明,C++ 标准 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.

[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 的规则进行。声明,而不管中间的案例标签。

关于c++ - 是否使用 if (0) 跳过应该工作的开关中的案例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64475978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com