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

Giving labels as a argument in C/C++

我们有一个标签:

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
}    

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

这听起来像 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;
    }
}

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

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