我有一个情况,我希望在C++切换语句中有两种情况都会下降到第三种情况.具体来说,第二个 case 将通过第三个 case ,第一个 case 也将通过第二个 case 通过第三个 case .
我有个愚蠢的 idea ,试了试,结果奏效了!我把第二个箱子装在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)中try 了一下,它做了同样的事情.
我的问题是:这是有效的C/C++吗?它应该做它该做的事吗?