4

I came across some code that looked like that below. I believe I understand what it does but I have no idea why it works and why it isn't a syntax error. I thought the if would have created a new scope and broken up the switch statement. How does the C/C++ compiler parse this?

switch(num) {
case 1:
    if (cond) {
case 2:
    foo();
    break;
    } else {
    bar();
    break;
    }
case 3:
    ...

For reference this is what gets called for different starting values:

(num = 1, cond = true ) -> foo()
(num = 2, cond = true ) -> foo()
(num = 1, cond = false) -> bar()
(num = 2, cond = false) -> foo()

Interestingly this does not appear to work in Java.

  • C != C++. Tag only with the language that you're using, unless both are actually relevant. – tambre Jan 26 '18 at 19:34
  • 2
    Related: https://en.wikipedia.org/wiki/Duff%27s_device – Bathsheba Jan 26 '18 at 19:36
  • 1
    Isn't this a legacy of switch/case being an evolved form of `goto` label (in C and C++ languages) causing case labels to ignore scoping rules? – user7860670 Jan 26 '18 at 19:38
  • 3
    Both C and C++ allow some [really surprising](http://amp-blog.robertelder.org/switch-statements-statement-expressions/) stuff inside `switch` statements. But it is all well dfined and legal - the rules are just "surprising" and "odd" in some cases. Good to know when modifying old code, but for new code; please avoid being surprising and/or odd. – Jesper Juhl Jan 26 '18 at 19:39
  • 3
    @JesperJuhl The title on that link is hilarious! `"_How to Get Fired Using Switch Statements & Statement Expressions_". – machine_1 Jan 26 '18 at 19:46
  • The `if` statement does create a new scope within the `switch` statement, but as far as the `case` labels are concerned, they're all within the body of the `switch`, which is all that matters. I'll argue this code is less than clear, but syntactically it's perfectly valid. – John Bode Jan 26 '18 at 22:30

0 Answers0