4 ms·
This features the construct switch(k) { if (0) case 0: x = 1; if (0) case 1: x = 2; if (0) default: x = 3; } which is a switch where you don't
by JonChesterfield 2y ago
This features the construct
switch(k) {
if (0) case 0: x = 1;
if (0) case 1: x = 2;
if (0) default: x = 3;
}
which is a switch where you don't have to write break at the end of every clause.
#define brkcase if (0) case
That might be worth using. Compilers won't love the control flow but they'll probably delete it effectively.
- leni536 2y agoSurely the following would work just as well? #define brkcase break;case kinda defeats the purpose of the macro even.
- MaxBarraclough 2y agoThat strikes me as better. The original macro presumably misbehaves if there's more than one statement in a sequence, as the if will only affect the first statement.
- wrsh07 2y agoI think the behavior is slightly different since this one breaks the above case, and the other one only omits its case from fallthrough Incidentally, what happens if you use your brkcase as the first case? I don't find either particularly exciting - a macro that would append break to the current case feels better
- leni536 2y agoBoth version of the macro makes this fall through from 0: switch (a) { brkcase 0: foo(); case 1: bar(); } so in a sense the `if (0) case` trick also affects the previous case, not the current one. But that one also falls apart when there are multiple statements under the brkcase.
- jppittma 2y agoI think it is super unclear how this works, and I would prefer the same control flow using goto, rather than the duffs device style switch abuses.
- asveikau 2y agoIt only works if the case label body is a single line or is enclosed in brackets. I'll confess, I've used this construct to mean "omit the first line of the next case label but otherwise fall through". If you think of the case label as merely a label and not a delimiter between statements all of this makes sense.