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

前端 未结 11 1535
说谎
说谎 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 17:06

    You might want to look at setjmp/longjmp.

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

    You can't do it with a goto - the labels have to be identifiers, not variables or constants. I can't see why you would not want to use a switch here - it will likely be just as efficient, if that is what is concerning you.

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

    It is possible with GCC feature known as "labels as values".

    void *s[3] = {&&s0, &&s1, &&s2};
    
    if (n >= 0 && n <=2)
        goto *s[n];
    
    s0:
    ...
    s1:
    ...
    s2:
    ...
    

    It works only with GCC!

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

    goto needs a compile-time label.

    From this example it seems that you are implementing some kind of state machine. Most commonly they are implemented as a switch-case construct:

    while (!finished) switch (state) {
      case s0:
      /* ... */
      state = newstate;
      break;
    
      /* ... */
    }
    

    If you need it to be more dynamic, use an array of function pointers.

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

    Optimizing compilers (including GCC) will compile a switch statement into a jump table (making a switch statement exactly as fast as the thing you're trying to construct) IF the following conditions are met:

    Your switch cases (state numbers) start at zero.

    Your switch cases are strictly increasing.

    You don't skip any integers in your switch cases.

    There are enough cases that a jump table is actually faster (a couple dozen compare-and-gotos in the checking-each-case method of dealing with switch statements is actually faster than a jump table.)

    This has the advantage of allowing you to write your code in standard C instead of relying on a compiler extension. It will work just as fast in GCC. It will also work just as fast in most optimizing compilers (I know the Intel compiler does it; not sure about Microsoft stuff). And it will work, although slower, on any compiler.

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