dat*_*ili 18 c++ compiler-errors switch-statement
可能重复:
为什么不能在switch语句中声明变量?
我的代码中有一个奇怪的错误:
char choice=Getchar();
switch(choice)
{
case 's':
cout<<" display tree ";
thetree->displaytree();
break;
case 'i':
cout<<" enter value to insert "<<endl;
cin>>value;
thetree->insert(value);
break;
case 'f' :
cout<< "enter value to find ";
cin>>value;
int found=thetree->find(value);
if(found!=-1)
cout<<" found = "<<value<<endl;
else
cout<< " not found " <<value <<endl;
break;
default:
cout <<" invalid entry "<<endl;;
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio 2010编译器说:
1>c:\users\daviti\documents\visual studio 2010\projects\2-3-4\2-3-4\2-3-4.cpp(317): error C2361: initialization of 'found' is skipped by 'default' label
1> c:\users\daviti\documents\visual studio 2010\projects\2-3-4\2-3-4\2-3-4.cpp(308) : see declaration of 'found'
Run Code Online (Sandbox Code Playgroud)
我认为我已经正确编写了break和default语句,那么错误在哪里?
Com*_* 10 58
你需要case 'f':
用一个范围的括号括起来:
case 'f' :
{
cout<< "enter value to find ";
cin>>value;
int found=thetree->find(value);
if(found!=-1)
cout<<" found = "<<value<<endl;
else
cout<< " not found " <<value <<endl;
break;
}
Run Code Online (Sandbox Code Playgroud)
或者放置found
外面的声明switch
Jam*_*nze 20
的语义switch
是那些的goto
:case
■不要引入一个新的范围.所以found
在你的default:
情况下是可访问的(虽然你实际上没有访问它).跳过非平凡的初始化是非法的,因此您的代码变得非法.
鉴于您的复杂性case 'f':
,最好的解决方案可能是将其分解为一个单独的功能.如果做不到这一点,您可以将整个案例放入{...}
,创建单独的作用域,或者放弃初始化,编写:
int found;
found = thetree->find(value);
Run Code Online (Sandbox Code Playgroud)
(我提到这是完整的.这不是我会推荐的解决方案.)
你需要在花括号内声明switch
's 的内部变量case
.即
case 'f' :
{
...
int found=thetree->find(value);
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21163 次 |
最近记录: |