Why can't variables be declared in a switch statement?

后端 未结 23 2977
一生所求
一生所求 2020-11-21 05:15

I\'ve always wondered this - why can\'t you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring

23条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 05:47

    A switch block isn't the same as a succession of if/else if blocks. I'm surprised no other answer explains it clearly.

    Consider this switch statement :

    switch (value) {
        case 1:
            int a = 10;
            break;
        case 2:
            int a = 20;
            break;
    }
    

    It may be surprising, but the compiler will not see it as a simple if/else if. It will produce the following code :

    if (value == 1)
        goto label_1;
    else if (value == 2)
        goto label_2;
    else
        goto label_end;
    
    {
    label_1:
        int a = 10;
        goto label_end;
    label_2:
        int a = 20; // Already declared !
        goto label_end;
    }
    
    label_end:
        // The code after the switch block
    

    The case statements are converted into labels and then called with goto. The brackets create a new scope and it is easy to see now why you can't declare two variables with the same name within a switch block.

    It may look weird, but it is necessary to support fallthrough (that is, not using break to let execution continue to the next case).

提交回复
热议问题