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.
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
I tried it in both C and C++ (both with clang), and it did the same thing.
My questions are: Is this valid C/C++? Is it supposed to do what it does?