C++ 转到变量

C++ Goto variable

有没有办法使用变量代替标签名称来调用 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;
}

我其实不是用这个的,我比较感兴趣的是学习

简答:没有。

长答案:没有。你为什么要这个?已经停止使用 goto

也许(只是猜测)您想要的是 std::functionswitch..

是也不是。没有这样的标准语言功能,但至少在 GCC 中是 compiler extension:

int main() {
    void* label;

    first:
    std::cout << "Hi";
    label = &&first;
    goto *label;
}

也就是说,我必须认真考虑一个比任何标准替代方案都更好的用例。

你问:

Is there a way to call a goto statement using a variable in the place of a label name?

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


您的假设示例

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

    return 0;
}

…在真实的 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 );
    }
}

这是一个简单的宏解决方案:

#define CALL_VARIALBLE(name) goto name;

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

    return 0;
}

您不能 goto 动态位置。

但是你可以看看POSIX setjmp/longjmp,它可以用来跳转到应用程序中的预定义位置。 MSVC 也支持。

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

void second(void) {
    printf("second\n");         // prints
    longjmp(buf,1);             // jumps back to where setjmp was called - making setjmp now return 1
}

void first(void) {
    second();
    printf("first\n");          // does not print
}

int main() {   
    if (!setjmp(buf))
        first();                // when executed, setjmp returned 0
    else                        // when longjmp jumps back, setjmp returns 1
        printf("main\n");       // prints

    return 0;
}