Reputation: 37
Why doesn't this goto work? After the player writes a number, it should boot them back to the main menu, instead, the compiler gives label MainMenu not defined c++
int main()
{
while (alive){
MainMenu:
}
}
void InfoPanel(){
int choice;
cout<<"1. Go back"<<endl;
cin>>choice;
if(choice==1){
goto MainMenu;
}
else{
goto MainMenu;
}
}
This is how the function is called
int MainMenuChoice;
cout<<"5.Open info panel"<<endl;
cin>>MainMenuChoice;
switch(MainMenuChoice){
case 1:
BuildingPanel();
break;
case 2:
ArmyPanel();
break;
case 3:
DiplomacyPanel();
break;
case 4:
ActionsPanel();
break;
case 5:
InfoPanel();
goto MainMenu;
break;
default:
cout<<"that doesnt seem to be correct";
goto MainMenu;
}
Upvotes: 0
Views: 1252
Reputation: 106
Your goto doesn't work because your label MainMenu: is not visible for Infopanel function as it`s defined in main and has scope visibility so it can be used just in main block.
Upvotes: 2
Reputation: 310980
From the C++ 14 Standard (3.3.5 Function scope)
1 Labels (6.1) have function scope and may be used anywhere in the function in which they are declared. Only labels have function scope.
And within the function InfoPanel
void InfoPanel(){
int choice;
cout<<"1. Go back"<<endl;
cin>>choice;
if(choice==1){
goto MainMenu;
}
else{
goto MainMenu;
}
}
the label MainMenu
is not defined. So the compiler issues an error message.
It is a bad idea to use the goto statement. Instead use a loop in main within which the function InfoPanel
will be called.
Upvotes: 4