有没有一种方法可以跳转到由 C 中的变量定义的行?

Is there a way to jump to a line defined by a variable in C?

所以,我有这个程序,我将行号存储在一个变量中,使用

int x = __LINE__;

x的值可以不断变化。 是否可以使用 goto 或 C 中的任何其他关键字从任意行跳转到 x 给定的行? 我正在寻找类似

的内容
'keyword' x;

程序转移到由变量 x 定义的行。

如果这不可能,是否有解决方法?

不,这是不可能的,实现类似功能的一种可能方法是将变量定义为函数指针,一旦将变量设置为 您调用它的正确函数。

int foo(int x) {
    return x+x;
}

int (*func) (int);
func = foo;
int r = func(3);

作为扩展,GCC 编译器支持 using labels as values 这样您就可以按照您想要的方式使用它们。

它允许你做:

void *ptr = &&label;
label:

然后

goto *ptr;

跳转到 label

这通常在虚拟机的核心内部很有用,当然会导致可怕的意大利面条。同样,它是一个 GCC 扩展(我认为也受 Clang 支持)。

这是可能的,但非常痛苦。假设你有这样一个程序:

instruction1;
instruction2;
...
instructionn;

那么你可以改写为:

jump:
switch(x) {
case 1:
  instruction1;
case 2:
  instruction2;
...
case n:
 instructionn;
}

然后您可以插入如下内容:

jump:
switch(x) {
case 1:
  instruction1;
case 2:
  instruction2;
...
case <something>:
  x = <number>;
  goto jump;
...
case n:
  instructionn;
}

当然你会在这样的模式中遇到编码像 switch 这样的块的问题,但是总是可以用这个给定的形式来翻译它(这里不是解释如何的地方)。所以根据你真正要做的事情,我可能不值得付出努力。