How to store goto labels in an array and then jump

2020-02-23 07:03发布

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 look like the following code:

function()
{
    "gotolabel" s[3];
    s[0] = s0;
    s[1] = s1;
    s[2] = s2;

    s0:
    ....
    goto s[v];

    s1:
    ....
    goto s[v];

    s2:
    ....
    goto s[v];
}

Does anyone have a idea how to perform this?

11条回答
\"骚年 ilove
2楼-- · 2020-02-23 07:19

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.

查看更多
三岁会撩人
3楼-- · 2020-02-23 07:20

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.

查看更多
别忘想泡老子
4楼-- · 2020-02-23 07:22

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

查看更多
Evening l夕情丶
5楼-- · 2020-02-23 07:23

could you use function pointers instead of goto?

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

查看更多
乱世女痞
6楼-- · 2020-02-23 07:23

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.

查看更多
ら.Afraid
7楼-- · 2020-02-23 07:25

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!

查看更多
登录 后发表回答