【问题标题】:error C2361: initialization of 'found' is skipped by 'default' label [duplicate]错误 C2361:“找到”的初始化被“默认”标签跳过 [重复]
【发布时间】:2012-05-10 00:04:02
【问题描述】:

可能重复:
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语句,那么错误在哪里?

【问题讨论】:

  • 如果您已经知道问题的答案,这只是一个完全相同的副本。神秘的“错误 C2361:'found' 的初始化被 'default' 标签跳过”并不一定会让您想到“为什么不能在 switch 语句中声明变量?”
  • 我今天遇到了同样的问题 :) 我不是 C++ 专业人士,我不知道不允许在没有花括号的“案例”中声明指针。所以只是一个想法,如果您知道答案或解决方案并想分享它,请分享,但不要在这里像个聪明人一样行事。
  • @Constantin 同意“自作聪明”的说法——但你指的是谁? :)

标签: c++ compiler-errors switch-statement


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    switch 的语义是 goto 的语义:cases 不是 引入一个新的范围。所以found 可以在您的default: 案例中访问 (尽管您实际上并没有访问它)。跳过一个不平凡的 初始化是非法的,所以你的代码是非法的。

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

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

    (为了完整起见,我提到了这一点。它不是我想要的解决方案 推荐。)

    【讨论】:

    • 赞成实际解释。
    • cases 不会引入新的作用域”——这句话说明了一切。
    【解决方案3】:

    您需要在花括号内声明switchcase 的内部变量。即

    case 'f' :
    {
        ...
        int found=thetree->find(value);
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多