您的位置:首页 > 编程语言 > C语言/C++

C++ 解决"Error: Jump to case label"的问题

2017-07-03 19:43 916 查看
【问题】代码如下

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!
}

【原因】case 1中声明的变量穿透到case 2中,但是这个变量在case 1中被初始化,但在case 2的作用域内并未初始化

【解决】

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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ Switch Case