就比如下面的代码,
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
会报如下的错,
initialization of 'newVal' is skipped by 'case' label
为什么会这样?
case
语句其实就是标签(label),就像 goto 语句那样,解决这个问题其实很简单,只需加一对大括号,以表明作用域即可,
switch (val)
{
case VAL:
{
// This will work
int newVal = 42;
break;
}
case ANOTHER_VAL:
...
break;
}