2

I had this doubt that why does gcc uses && to access a label and why it doesn't directly gives access to the value of location associated with the label. like in the following piece of code :

void main()
{
    static void* loc = &&locA;
    printf("locA : %p\n", locA); //will give error
    printf("loc : %p\n",loc); //will not give error
    //statments X
    locA :
    //statements Y

}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Akhil
  • 105
  • 1
  • 8
  • You might find the answer here: http://stackoverflow.com/questions/1777990/is-it-possible-to-store-the-address-of-a-label-in-a-variable-and-use-goto-to-jum The TL;DR is probably: because obtaining the address of a label isn't supported by the C and C++ standards. – Petr Skocik Oct 09 '15 at 01:33
  • 2
    Oh wow I didn't even know gcc could do this. As far as I know MSVC doesn't support this -- not that I've really used `goto` much, but still good to know now! – Blindy Oct 09 '15 at 01:41
  • @Blindy : If using MSVC in 32 bit code (not x64) you can access the label's address with inline assembly. `void* loc; __asm{ mov [loc],offset locA }; locA:` – Michael Petch Oct 09 '15 at 02:00
  • I have to agree with @Olaf 's opinion though - if you have to use a non standard compliant way of doing something, you might be better off reworking your code to find a standard compliant way of achieving the same goal. – Michael Petch Oct 09 '15 at 02:22

1 Answers1

2

This is a gcc extension as document Extensions to the C Language Family of the gcc documentation in the section Labels as Values which says:

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;

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

 goto *ptr;

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];
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740