Ok so i've been working on this menu program for a while now, using various methods. I decided to give Goto a try even though people recommened not using it. However this program works well and has been the most effective method so far without any faults.
My question is, what are the alternatives to Goto? is there a more simplified (working) method for what I want to achieve?
The command "goto" is a tool, just like everything else in C and C++. It has it's uses otherwise it would not be included in the language. The biggest problem I've seen with "goto" is that people who end up using it early on in their learning make some crazy concession in their code in order for it to work, where there are often better solutions.
state = MAIN_MENU;
while (running){
switch (state){
case MAIN_MENU:
state = Options();
break;
case OPTION_1:
system("CLS");
state = Options() + SECOND_MENU;
break;
case OPTION_1 + SECOND_MENU:
system("CLS");
state = Sound() + THIRD_MENU;
break;
case OPTION_1 + THIRD_MENU:
state = OPTION_1;
break;
case OPTION_2 + THIRD_MENU:
exit(0);
case OPTION_OTHER + THIRD_MENU:
break;
case OPTION_2 + SECOND_MENU:
system("CLS");
state = MAIN_MENU;
break;
case OPTION_2:
running = false;
break;
case OPTION_OTHER:
//In reality, this code should be part of Options(). I only put it
//here for the sake of the example.
cout << "Incorrect selection, please choose again\n" << endl;
cin.get();
state = MAIN_MENU;
break;
}
}
I would still not use goto in this application. Actually some of the goto's here are not necessary since the program execution shall automatically reach the spot you intended without the goto call.
Moreover, I would break the nested switch statements into different functions. It would improve readability and make debugging a lot easier.
while(running !=false)
{
Menu();
switch(choice)
{
case 1:
system("CLS");
Options();
// this function handles the new choice. The return value decides whether
// the Menu is to be run again or not.
running = handle(choice2);
break;
case 2:
running = false;
break;
default:
cout << "Incorrect selection, please choose again\n" << endl;
cin.get();
}
}
Just a note: if you place Menu() outside the program loop and call it in the loop because of some user error, it does what you want.
That's how i've avoided goto. It restarts the program from where Menu() was first called like you would do with your first goto.
i.e.
1 2 3 4 5 6 7 8 9 10 11 12 13
Menu (); //point 1
while (running)
{
switch (choice)
{
case 1:
//blah
case 2:
//blah
default:
Menu(); //this restarts the program from point 1
}