【问题标题】:initialization of 'element' is skipped by 'case' label [duplicate]'case'标签跳过'element'的初始化[重复]
【发布时间】:2013-01-18 03:10:39
【问题描述】:

我不明白为什么会出现错误:

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

谁能给我解释一下?

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;
    }
}

【问题讨论】:

  • 那个错误很明显,switch语句的使用也很奇怪。
  • 每个case 都不会引入新的作用域(只有{ } 块会这样做)。所以当你在一个 case 中声明一个变量时,它应该放在它自己的块中。

标签: c++ debugging


【解决方案1】:

尝试用{} 包裹case,并将所有语句放入{}

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

您应该将所有这些语句放在函数中,保持case 语句清晰。比如写成这样的样式:

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

link

【讨论】:

  • @biliz 为什么放 { } 可以解决问题???
  • 作用域问题,case: 直到break 才引入新作用域,所以你必须使用{}
  • 我还是不太明白,有什么文章可以看的更明白???
【解决方案2】:

当一个变量在一个case 中声明时,下一个case 在技术上仍然在同一个范围内,所以你可以在那里引用它,但是如果你点击那个case 而没有先点击这个,你最终会调用一个未初始化的变量。这个错误可以防止这种情况。

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

【讨论】:

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