C++ “元素”的初始化被“案例”标签跳过

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14669457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:34:16  来源:igfitidea点击:

initialization of 'element' is skipped by 'case' label

c++debugging

提问by Computernerd

I don't understand why I am getting the error:

我不明白为什么我收到错误:

initialization of 'element' is skipped by 'case' label.

“元素”的初始化被“案例”标签跳过。

Can someone please explain to me?

有人可以向我解释一下吗?

void LinkedList::process_example(int choice) {
    switch(choice) {
    case 1:
        cout << endl << endl << "Current S = ";
        this->printSet();

        cout << "Enter an element :";
        char* element = "lol";

        //cin>>element;
        cin.clear();
        cin.ignore(200, '\n');

        this->Addelementfromback(element); //error is here
        cout << endl << endl << "Current S = ";

        this->printSet();
        break;

    case 2:
        this->check_element();
        break;

    case 3:
        cout << endl << endl;
        cout << "Current Set S = ";
        this->printSet();

        cout << endl << "S has ";
        int count = this ->check_cardinality();
        cout << count << " elements";
        break;
    }
}

回答by billz

Try wrap casewith {}, and put all your statement inside {}.

尝试包case{},并把你的所有语句内{}

case 1:
{
   cout << endl << endl << "Current S = ";
   this->printSet();    
   // and other mess
}
break;

You should put all these statement in functions, keep casestatement clear. For example, write this style:

你应该把所有这些语句放在函数中,保持case语句清晰。例如,编写这种样式:

case 1:
   initializeElement();
   break;
case 2:
   doSomethingElse();
   break;

See link

链接

回答by Rhys Thompson

When a variable is declared in one case, the next caseis technically still in the same scope so you could reference it there but if you hit that casewithout hitting this one first you would end up calling an uninitialised variable. This error prevents that.

当一个变量在 one 中声明时case,下一个case在技​​术上仍然在相同的范围内,因此您可以在那里引用它,但是如果您case没有先点击这个就点击它,您最终会调用一个未初始化的变量。这个错误阻止了这一点。

All you need to do is either define it before the switchstatement or use curly braces { }to make sure it goes out of scope before exiting a specific case.

您需要做的就是在switch语句之前定义它或使用花括号{ }确保它在退出特定的case.