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

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

    You can declare variables within a switch statement if you start a new block:

    switch (thing)
    { 
      case A:
      {
        int i = 0;  // Completely legal
      }
      break;
    }
    

    The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).

提交回复
热议问题