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

后端 未结 23 3033
一生所求
一生所求 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 06:12

    I just wanted to emphasize slim's point. A switch construct creates a whole, first-class-citizen scope. So it is posible to declare (and initialize) a variable in a switch statement before the first case label, without an additional bracket pair:

    switch (val) {  
      /* This *will* work, even in C89 */
      int newVal = 42;  
    case VAL:
      newVal = 1984; 
      break;
    case ANOTHER_VAL:  
      newVal = 2001;
      break;
    }
    

提交回复
热议问题