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

后端 未结 23 3050
一生所求
一生所求 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条回答
  •  梦毁少年i
    2020-11-21 05:52

    Most of the replies so far are wrong in one respect: you can declare variables after the case statement, but you can't initialize them:

    case 1:
        int x; // Works
        int y = 0; // Error, initialization is skipped by case
        break;
    case 2:
        ...
    

    As previously mentioned, a nice way around this is to use braces to create a scope for your case.

提交回复
热议问题