Search code examples
c++scopelabelgoto

Goto label not defined c++


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

Solution

  • 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.