How to store goto labels in an array and then jump to them?

前端 未结 11 1534
说谎
说谎 2020-12-28 16:20

I want to declare an array of \"jumplabels\".

Then I want to jump to a \"jumplabel\" in this array.

But I have not any idea how to do this.

It should

相关标签:
11条回答
  • 2020-12-28 16:48

    For a simple answer, instead of forcing compilers to do real stupid stuff, learn good programming practices.

    0 讨论(0)
  • 2020-12-28 16:55

    There's no direct way to store code addresses to jump to in C. How about using switch.

    #define jump(x)  do{ label=x; goto jump_target; }while(0)
    int label=START;
    jump_target:
    switch(label)
    {
        case START:
            /* ... */
        case LABEL_A:
            /* ... */
    }
    

    You can find similar code produced by every stack-less parser / state machine generator. Such code is not easy to follow so unless it is generated code or your problem is most easily described by state machine I would recommend not do this.

    0 讨论(0)
  • 2020-12-28 17:01

    Tokenizer? This looks like what gperf was made for. No really, take a look at it.

    0 讨论(0)
  • 2020-12-28 17:02

    could you use function pointers instead of goto?

    That way you can create an array of functions to call and call the appropriate one.

    0 讨论(0)
  • 2020-12-28 17:03

    That's what switch statements are for.

    switch (var)
    {
    case 0:
        /* ... */
        break;
    case 1:
        /* ... */
        break;
    default:
        /* ... */
        break;  /* not necessary here */
    }
    

    Note that it's not necessarily translated into a jump table by the compiler.

    If you really want to build the jump table yourself, you could use a function pointers array.

    0 讨论(0)
  • 2020-12-28 17:06

    In plain standard C, this not possible as far as I know. There is however an extension in the GCC compiler, documented here, that makes this possible.

    The extension introduces the new operator &&, to take the address of a label, which can then be used with the goto statement.

    0 讨论(0)
提交回复
热议问题