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

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

    New variables can be decalared only at block scope. You need to write something like this:

    case VAL:  
      // This will work
      {
      int newVal = 42;  
      }
      break;
    

    Of course, newVal only has scope within the braces...

    Cheers, Ralph

提交回复
热议问题