如何在 C 中有条件地分支到由算术运算或查找给出的标签 table

How to branch conditionally in C to a label given by an arithmetic operation or lookup table

而不是像这样写 ifswitch 语句:

if (a == 1)
    <some code here 1>
else if (a == 2)
    <some code here 2>
else if (a == 3)
    <some code here 3>

我想要运行这样的东西:

l[1] = here1;
l[2] = here2;
l[3] = here3;

goto l[a];

here1:
    <some code here 1>
here2:
    <some code here 2>
here3:
    <some code here 3>

是否可以在 C 中执行此操作?

不,不是,但是有一个 GCC 扩展。 https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html#Labels-as-Values.

因此您的代码将是:

void *l[3] = {&&here1, &&here2, &&here2};

goto *l[a];

here1:
    <some code here 1>
here2:
    <some code here 2>
here3:
    <some code here 3>