C++转到变量

eso*_*ote 4 c++ variables goto

有没有办法在标签名称的位置使用变量调用goto语句?

我正在寻找类似的东西(这对我不起作用):

// std::string or some other type that could represent a label
void callVariable(std::string name){
    goto name;
}

int main(){
    first:
    std::cout << "Hi";
    callVariable(first);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我实际上并没有使用它,我对学习更感兴趣.

chr*_*ris 12

是的,不是.没有这样的标准语言功能,但它至少是GCC中的编译器扩展:

int main() {
    void* label;

    first:
    std::cout << "Hi";
    label = &&first;
    goto *label;
}
Run Code Online (Sandbox Code Playgroud)

也就是说,我必须努力思考一个比任何标准替代品更好的用例.

  • @sparc_spread:这不是黑客。这是一种语言扩展。 (2认同)
  • @Jesper Juhl那就是"不......会(或应该)使用"免责声明部分是关于:-) (2认同)

Che*_*Alf 5

你问:

有没有办法使用变量代替标签名称来调用 goto 语句?

是的,C++ 中提供这种效果的功能称为switch. 它在语法上不涉及单词goto。但是它会跳转到由变量指定的标签,因此,您可以使用它模拟各种基于脏goto的代码,包括早期的 Basic 的on ... goto ....


你的假设例子

int main(){
    first:
    std::cout << "Hi";
    callVariable(first);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

...在真正的 C++ 中看起来像这样:

#define CALL_VARIABLE( where ) next_jump = where; break;

auto main()
    -> int
{
    enum Label {first, second, third};
    Label next_jump = first;
    for( ;; ) switch( next_jump )
    {
    case first:
        std::cout << "Hi";
        CALL_VARIABLE( first );
    }
}
Run Code Online (Sandbox Code Playgroud)