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

后端 未结 23 2970
一生所求
一生所求 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
    慢半拍i (楼主)
    2020-11-21 05:48

    After reading all answers and some more research I get a few things.

    Case statements are only 'labels'
    

    In C, according to the specification,

    §6.8.1 Labeled Statements:

    labeled-statement:
        identifier : statement
        case constant-expression : statement
        default : statement
    

    In C there isn't any clause that allows for a "labeled declaration". It's just not part of the language.

    So

    case 1: int x=10;
            printf(" x is %d",x);
    break;
    

    This will not compile, see http://codepad.org/YiyLQTYw. GCC is giving an error:

    label can only be a part of statement and declaration is not a statement
    

    Even

      case 1: int x;
              x=10;
                printf(" x is %d",x);
        break;
    

    this is also not compiling, see http://codepad.org/BXnRD3bu. Here I am also getting the same error.


    In C++, according to the specification,

    labeled-declaration is allowed but labeled -initialization is not allowed.

    See http://codepad.org/ZmQ0IyDG.


    Solution to such condition is two

    1. Either use new scope using {}

      case 1:
             {
                 int x=10;
                 printf(" x is %d", x);
             }
      break;
      
    2. Or use dummy statement with label

      case 1: ;
                 int x=10;
                 printf(" x is %d",x);
      break;
      
    3. Declare the variable before switch() and initialize it with different values in case statement if it fulfills your requirement

      main()
      {
          int x;   // Declare before
          switch(a)
          {
          case 1: x=10;
              break;
      
          case 2: x=20;
              break;
          }
      }
      

    Some more things with switch statement

    Never write any statements in the switch which are not part of any label, because they will never executed:

    switch(a)
    {
        printf("This will never print"); // This will never executed
    
        case 1:
            printf(" 1");
            break;
    
        default:
            break;
    }
    

    See http://codepad.org/PA1quYX3.

提交回复
热议问题