Why does this if statement overlap the case block in the switch statement?

I came across some kind of code that looks like this below. I believe that I understand what he is doing, but I have no idea why this works and why this is not a syntax error. I thought I ifwould create a new scope and break 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 initial 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 work in Java.

+4
source share

Source: https://habr.com/ru/post/1692783/


All Articles