转到标签未定义 C++

Goto label not defined c++

为什么这个 goto 不起作用?播放器写入数字后,应该将它们引导回主菜单,相反,编译器给出标签 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;
    }
}

函数是这样调用的

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

来自 C++ 14 标准(3.3.5 函数作用域)

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.

并在函数内InfoPanel

void InfoPanel(){
    int choice;

    cout<<"1. Go back"<<endl;
    cin>>choice;
    if(choice==1){
        goto MainMenu;
    }
    else{
        goto MainMenu;
    }
}

标签 MainMenu 未定义。所以编译器发出错误信息。

使用 goto 语句是个坏主意。而是在 main 中使用一个循环,在该循环中将调用函数 InfoPanel

您的 goto 不起作用,因为您的标签 MainMenu:Infopanel[=16= 中不可见] 在 main 中定义的函数并且具有范围可见性,因此它只能在主块中使用。