switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
改成:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
原因:一個 case 條件下的變量在其他 case 條件下依然可見,然而其初始化語句是屬于單個 case 的,就導緻了其他的 case 中的該變量未初始化,是以要記得加上花括号{}以限定作用域。