C language > Expert questions

Computed goto?

(1/2) > >>

Akko:
In gcc 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;
/* … */
foo:       // label
/* … */
ptr = &&foo;


To use these values, you need to be able to jump to one. This is done with the computed goto Statement: goto *exp;.
For example,

goto *ptr;

How to do this in Pelles C ???

frankie:
This is a GCC extension, and is not part of C standard.
PellesC doesn't implement this extension.
To create jump tables you must use standard switch statement.

Bitbeisser:
Thanks for giving me one more reason to hate GCC...

Ralf

frankie:
This feature make sense only when used for OS kernel modules, where the coder can build the equivalent of an assembler jump-table. And it should allow even the implementation of inter-routines jumps, known as coroutines.
In fact while the documentation says that the programmer should avoid to use labels defined in different routines in local jumps, don't explicitly states that they are blocked by the compiler.
The advantage over the standard switch statement is that it is someway invisible to the optimizations, and allows more control over code for the programmer.
I don't know how much it is used in the Linux kernel, but if it's there it should be of some use  ???
Anyway for standard programming it must be avoided (in GCC obviously, the other compilers don't have it!). An inexpert programmer can create jumps between incompatible functions call (i.e. different number of parameters) leading to stack or, more generally, memory corruption and consequential program crash.
Inter-functions jumps are still permitted using the standard int setjmp(jmp_buf env)/void longjmp(jmp_buf env, int value) functions from setjmp.h.

Akko:

--- Quote from: frankie on November 18, 2018, 08:36:55 PM ---This is a GCC extension, and is not part of C standard.
PellesC doesn't implement this extension.
To create jump tables you must use standard switch statement.

--- End quote ---

"Labels as values" are a C language extension indeed, AFAIK also supported by clang, perhaps other compilers as well.

The most prominent usage of label as value is in interpreters for threaded code.

The labels within the interpreter function can be stored in the threaded code for super-fast dispatching,
a popular method for building virtual machines.

Navigation

[0] Message Index

[#] Next page

Go to full version