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

后端 未结 23 2986
一生所求
一生所求 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: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();
    }
    

提交回复
热议问题