Do all compilers support goto label addresses?

Viewed 54

I was looking at this block of code:

int main() {
    void *labels[] = { &&label1, &&label2 };

    goto *labels[1];

  label1:
    printf("Label 1\n");

  label2:
    printf("Label 2\n");

    return 0;
}

I was wondering if this is a normal thing and can be expected in any compiler.

1 Answers

it's one of the GCC compilers features , refer to labels as Values in GCC manual , they clearly state that :

You can get the address of a label defined in the current function (or a containing function) with the unary operator ‘&&’. The value has type void *. This value is a constant and can be used wherever a constant of that type is valid. For example:

void *ptr;
/* … */
ptr = &&foo;

where foo is just a label , so yeah , you can deal with labels as addresses in GCC compiler according to the manual.

even they have this example that is nearly same as yours as they stated that :

One way of using these constants is in initializing a static array that serves as a jump table:

 static void *array[] = { &&foo, &&bar, &&hack };

Then you can select a label with indexing, like this:

 goto *array[i];

but it's a feature in GCC compiler , so whatever the compiler you use , refer to its manual and you should know if this feature is supported or not.

but also remember that , it's not a good practice to use label and goto in your code if you are coding for critical system which sticks to strict rules as according to MISRA C in section 8.15 Control flow , they clearly stated that :

Rule 15.1 The goto statement should not be used

so then it might be better to say that using goto is a fine practice when used thoughtfully and judiciously so long as it is not applied in a codebase that observes such strict guidelines.

Related