C++ Goto variable

C++ Goto variable

本文关键字:variable Goto C++      更新时间:2023-10-16

是否有一种方法可以在标签名称的位置使用变量调用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;
}

我不是真的在用这个,我对学习更感兴趣。

是,不是。没有这样的标准语言特性,但它至少在GCC中是一个编译器扩展:

int main() {
    void* label;
    first:
    std::cout << "Hi";
    label = &&first;
    goto *label;
}

这就是说,我必须努力思考一个用例,它比任何标准替代方案都好。

你问:

是否有一种方法可以在标签名称的位置使用变量调用goto语句?

是的,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 );
    }
}

简短的回答:no.

长话短说:没有。你为什么想要这个?别再用goto了。

也许(只是猜测)你想要的是一个std::functionswitch代替…

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

#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("secondn");         // prints
    longjmp(buf,1);             // jumps back to where setjmp was called - making setjmp now return 1
}
void first(void) {
    second();
    printf("firstn");          // does not print
}
int main() {   
    if (!setjmp(buf))
        first();                // when executed, setjmp returned 0
    else                        // when longjmp jumps back, setjmp returns 1
        printf("mainn");       // prints
    return 0;
}