为什么不能在 switch 语句中声明变量?
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 them close to first use is obviously a good thing) but the following still won't work:
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
The above gives me the following error (MSC):
initialization of 'newVal' is skipped by 'case' label
This seems to be a limitation in other languages too. Why is this such a problem?
转载于:https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement
笑故挽风
2008/09/18 13:11- switch-statement
- c++
- 点赞
- 收藏
- 回答
满意答案
23个回复
