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.