在C / C ++中将标签作为参数

时间:2016-08-04 12:51:53

标签: c++11 goto

我们有一个标签:

LABEL:
    //Do something.

我们有一个功能。我们希望传递LABEL作为此函数的参数(否则我们无法访问函数中的标签),并且在某些情况下我们想要跳转此标签。可能吗?

我举一个例子(伪代码)来澄清:

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
}    

3 个答案:

答案 0 :(得分:5)

这听起来像XY problem。您可能需要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;
    }
}

答案 1 :(得分:1)

似乎值得将代码重构为类似的东西:

void GameMenu() {
    // Show menu
}

void SomethingElse() {
    // Do something else
}

int main(int argc, char **argv) {

    (...)

    while(Game.running) {
        int key = GetKey();
        switch(key) {
        case ESCAPE:
            GameMenu();
            break;
        case OTHER_KEY:
            SomethingElse();
            break;
        }
    }
}

答案 2 :(得分:-1)

您可以使用setjmp()/longjmp()跳转到外部范围中的某个点甚至外部函数。但请注意 - 跳跃目标范围必须在跳跃时保持活跃状态​​。