C ++转到变量

时间:2016-09-03 00:07:36

标签: 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;
}

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

5 个答案:

答案 0 :(得分:12)

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

int main() {
    void* label;

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

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

答案 1 :(得分:5)

简答:不。

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

也许(只是猜测)你想要的是std::functionswitch而不是......

答案 2 :(得分:4)

你问:

  

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

是的,C ++中提供该效果的功能称为switch。它在语法上不涉及单词goto。但它跳转到变量指定的标签,因此,使用它可以模拟各种基于goto的脏代码,包括早期的基本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 );
    }
}

答案 3 :(得分:2)

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

#define CALL_VARIALBLE(name) goto name;

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

    return 0;
}

答案 4 :(得分:2)

您无法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;
}