20

可能重复:
为什么不能在 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;;
    }

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'

我认为我已经正确编写了 break 和 default 语句,那么错误在哪里?

4

3 回答 3

60

您需要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-30T09:23:14.843 回答
24

a 的语义是 a 的语义switchgotoscase不会引入新的范围。所以found在你的default:情况下是可以访问的(尽管你实际上并没有访问它)。跳过非平凡的初始化是非法的,因此您的代码变得非法。

鉴于您的复杂性case 'f':,最好的解决方案可能是将其分解为一个单独的函数。如果做不到这一点,您可以将整个案例放入 中{...},创建一个单独的范围,或者放弃初始化,编写:

int found;
found = thetree->find(value);

(我提到这一点是为了完整性。这不是我推荐的解决方案。)

于 2012-04-30T09:27:26.897 回答
7

您需要在花括号内声明switch'的内部变量。caseIE

case 'f' :
{
    ...
    int found=thetree->find(value);
    ...
}
于 2012-04-30T09:17:22.750 回答