Search code examples
cgoto

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


So, I have this program, where I store the line number in a variable, using

int x = __LINE__;

The value of x can keep changing. Is it possible to jump from an arbitrary line to the one given by x, using goto or any other keyword in C? I'm looking for something like

'keyword' x;

where the program shifts to a line defined by the variable x.

Is there a workaround if this is not possible?


Solution

  • The GCC compiler supports, as an extension, using labels as values so that you can work with them in a way that resembles what you're after.

    It allows you to do:

    void *ptr = &&label;
    label:
    

    and then

    goto *ptr;
    

    to jump to label.

    This is typically useful inside the core of a virtual machine, and can of course lead to horrible spaghetti. Also, again, it's a GCC extension (also supported by Clang, I think).