93

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;
    }
}
Foggzie
  • 9,691
  • 1
  • 31
  • 48
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • That error is pretty clear, also very odd use of a switch statement. – Rapptz Feb 03 '13 at 04:21
  • 12
    Each `case` does not introduce a new scope (only `{ }` blocks do that). So when you declare a variable inside one case, it should put be within its own block. – Cameron Feb 03 '13 at 04:29

2 Answers2

169

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

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

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

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

See link

Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
15

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

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

Peter Tretyakov
  • 3,380
  • 6
  • 38
  • 54
Rhys Thompson
  • 151
  • 1
  • 2