c++ - 错误 C2361 : initialization of 'found' is skipped by 'default' label

标签 c++ compiler-errors switch-statement

Possible Duplicate:
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 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语句,那么错误在哪里?

最佳答案

您需要将 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

之外

关于c++ - 错误 C2361 : initialization of 'found' is skipped by 'default' label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381144/

相关文章:

c++ - Rcpp 将 vector 复制到 vector

qt - 尝试在 Debian 上针对 win32 交叉编译 Qt 4.8.3 时构建失败

c# - 当你的算法已经处理它时处理 "not all code paths return a value"的技术

java - 无法在 Java 中调用通用对象的方法

java - 在 Java 中使用 case 时使用 Break 的替代方法

java - 交换机不兼容类型错误

c++ - TEA中加密和解密结果不一样

c++ - 是否有基于宏的适配器来从类中创建仿函数?

c++ - 将 listS 用于顶点和边列表时无法调用 boost::clear_vertex

c - 在 Switch 语句中使用字母