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

后端 未结 23 2974
一生所求
一生所求 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: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.

    0 讨论(0)
  • 2020-11-21 05:52

    newVal exists in the entire scope of the switch but is only initialised if the VAL limb is hit. If you create a block around the code in VAL it should be OK.

    0 讨论(0)
  • 2020-11-21 05:54

    Try this:

    switch (val)
    {
        case VAL:
        {
            int newVal = 42;
        }
        break;
    }
    
    0 讨论(0)
  • 2020-11-21 05:57

    You can declare variables within a switch statement if you start a new block:

    switch (thing)
    { 
      case A:
      {
        int i = 0;  // Completely legal
      }
      break;
    }
    

    The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).

    0 讨论(0)
  • 2020-11-21 05:57

    Consider:

    switch(val)
    {
    case VAL:
       int newVal = 42;
    default:
       int newVal = 23;
    }
    

    In the absence of break statements, sometimes newVal gets declared twice, and you don't know whether it does until runtime. My guess is that the limitation is because of this kind of confusion. What would the scope of newVal be? Convention would dictate that it would be the whole of the switch block (between the braces).

    I'm no C++ programmer, but in C:

    switch(val) {
        int x;
        case VAL:
            x=1;
    }
    

    Works fine. Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

    0 讨论(0)
  • 2020-11-21 05:57

    So far the answers have been for C++.

    For C++, you can't jump over an initialization. You can in C. However, in C, a declaration is not a statement, and case labels have to be followed by statements.

    So, valid (but ugly) C, invalid C++

    switch (something)
    {
      case 1:; // Ugly hack empty statement
        int i = 6;
        do_stuff_with_i(i);
        break;
      case 2:
        do_something();
        break;
      default:
        get_a_life();
    }
    

    Conversly, in C++, a declaration is a statement, so the following is valid C++, invalid C

    switch (something)
    {
      case 1:
        do_something();
        break;
      case 2:
        int i = 12;
        do_something_else();
    }
    
    0 讨论(0)
提交回复
热议问题