Switch-Case: declaration-with-initialization & declaration-and-then-assignment

后端 未结 2 419
谎友^
谎友^ 2021-01-18 07:50

In the switch-case statements declaration-with-initialization is invalid but declaration-and-then-assignment is allowed. As shown in the fo

2条回答
  •  -上瘾入骨i
    2021-01-18 08:01

    In fact, neither are legal C++. You cannot declare a variable in a switch case unless it is scoped:

    switch(val)  
    {  
    case 0:  
      {
        int newVal = 42;  // now valid
      }
      break;
    case 1:  
      {
        int newVal2;      // still Valid
        newVal2 = 42;  
      }
      break;
    case 2:
      break;
    }
    

    The fact that your compiler permits case 1 is a defect of your compiler, or possibly an extension. At least, according to the standard.

提交回复
热议问题