Search code examples
c++11goto

Giving labels as a argument in C/C++


We have a label:

LABEL:
    //Do something.

and we have a function. We want pass LABEL as a argument to this function (otherwise we can't access labels in a function), and in some condition we want to jump this label. Is it possible?

I'm giving a example (pseudocode) for clarification:

GameMenu: //This part will be executed when program runs
//Go in a loop and continue until user press to [ENTER] key

while(Game.running) //Main loop for game
{
    Game.setKey(GameMenu, [ESCAPE]); //If user press to [ESCAPE] jump into GameMenu
    //And some other stuff for game
}    

Solution

  • This sounds like an XY problem. You might want a state machine:

    enum class State {
        menu,
        combat,
    };
    
    auto state = State::combat;
    while (Game.running) {
        switch (state) {
        case State::combat:
            // Detect that Escape has been pressed (open menu).
            state = State::menu;
            break;
    
        case State::menu:
            // Detect that Escape has been pressed (close menu).
            state = State::combat;
            break;
        }
    }