0
int menuDecision = displayMenu();

  //WHILE USER DOESN'T SELECT QUIT
while(menuDecision != 3){
/*
    if(menuDecision == 1){
        Queue myQueue;
    }
    else{
        Stack myStack;
    }
*/

    switch(menuDecision){
        case 1: Queue myQueue;
                break;
        case 2: Stack myStack;
                break;
    }

    menuDecision = displayMenu();

}

How come when I run the above as a switch statement it's giving me an error but when I use the if/else-if it works? Basically the program instantiates an object depending on what is selected in the menu.Once an object is created the constructor is called, and the constructor calls another function and so on...Basically a new object is created each pass in the while Loop. Since I'm not getting a lot of feedback in my code, would the above implementation be considered 'bad programming'?

Thanks!

Edit: The error is:

main.cpp:27:4: error: cannot jump from switch statement to this case label
                        case 2: Stack myStack;
                        ^
main.cpp:25:18: note: jump bypasses variable initialization
                        case 1: Queue myQueue;
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154

1 Answers1

5

C++ does not allow switches (or other similar code, such as goto) to jump over initialisations . In the switch, both the Queue and the Stack are at the same scope, and it would be possible for the switch code not to initialise one (or both) of them in that scope, depending on the value being switched on. This isn't so for the if/else, where they are at different scopes.