Hacker News new | ask | show | jobs
by JonChesterfield 715 days 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.
3 comments

Surely the following would work just as well?

  #define brkcase break;case
kinda defeats the purpose of the macro even.
That 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.
I 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

Both 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.
I 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.
It 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.