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

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

    C++ Standard has: It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).

    The code to illustrate this rule:

    #include 
    
    using namespace std;
    
    class X {
      public:
        X() 
        {
         cout << "constructor" << endl;
        }
        ~X() 
        {
         cout << "destructor" << endl;
        }
    };
    
    template 
    void ill_formed()
    {
      goto lx;
    ly:
      type a;
    lx:
      goto ly;
    }
    
    template 
    void ok()
    {
    ly:
      type a;
    lx:
      goto ly;
    }
    
    void test_class()
    {
      ok();
      // compile error
      ill_formed();
    }
    
    void test_scalar() 
    {
      ok();
      ill_formed();
    }
    
    int main(int argc, const char *argv[]) 
    {
      return 0;
    }
    

    The code to show the initializer effect:

    #include 
    
    using namespace std;
    
    int test1()
    {
      int i = 0;
      // There jumps fo "case 1" and "case 2"
      switch(i) {
        case 1:
          // Compile error because of the initializer
          int r = 1; 
          break;
        case 2:
          break;
      };
    }
    
    void test2()
    {
      int i = 2;
      switch(i) {
        case 1:
          int r;
          r= 1; 
          break;
        case 2:
          cout << "r: " << r << endl;
          break;
      };
    }
    
    int main(int argc, const char *argv[]) 
    {
      test1();
      test2();
      return 0;
    }
    

提交回复
热议问题