可能重复:
Why can't variables be declared in a switch statement?
下面的代码中有一个奇怪的错误:
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;;
}Visual 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'我认为我已经正确地写了中断和默认语句,那么错误在哪里呢?
发布于 2012-04-30 09:23:14
您需要用限定范围的大括号将您的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;
}或者将found的声明放置在switch之外
发布于 2012-04-30 09:27:26
switch的语义是goto的语义:case没有引入新的范围。因此,found在您的default:中是可访问的(尽管您实际上没有访问它)。跳过一个非平凡的初始化是非法的,所以您的代码成为非法的。
考虑到case 'f':的复杂性,最好的解决方案可能是将其分解为单独的函数。否则,您可以将整个案例放在{...}中,创建一个单独的作用域,或者放弃初始化,编写:
int found;
found = thetree->find(value);(为了完整起见,我提到这一点。这不是我要重新评论的解决方案。)
发布于 2012-04-30 09:17:22
您需要在大括号内声明switch's case的内部变量。
case 'f' :
{
...
int found=thetree->find(value);
...
}https://stackoverflow.com/questions/10381144
复制相似问题