开发者

What does && mean in void *p = &&abc;

I came across a piece of code void *p = &&abc;. What is the significance of && here? I know about rvalue references but I think &开发者_C百科amp;& used in this context is different. What does && indicate in void *p = &&abc; ?


&& is gcc's extension to get the address of the label defined in the current function.

void *p = &&abc is illegal in standard C99 and C++.

This compiles with g++.


How to find it out

That's the address of a label and it's a feature specific to GCC.

int main(void) {
    void* startp;
s:
    startp = &&s;
    printf("the assignment above starts at address %p\n", startp);
    return 0;
}

You could have figured it out yourself by testing:

int main(void) {
    void* startp;
    int a;
    startp = &&a;
    printf("startp=%p\n", startp);
    return 0;
}

In which case GCC says:

error: label ‘a’ used but not defined

Under the hood - assembly

You need to know assembler to really understand this, but I'll try to explain you what an address of a label means.

After the OS loads the .exe file from the disk, a component of the operating system called "the loader" (windows has the "PE Loader", linux has "ELF loader" or maybe even others, if they're compiled in the kernel), it does a "virtualization" of that program, turning it into a process.

This process thinks it is the only one in RAM and it has access to the entire RAM (that is, 0x00000000-0xFFFFFFFF on a 32-bit machine).

(the above is just a short overwiew of what's happenning, you really need to learn assembly to understand it fully, so bear with me)

Now, the label in a source code is basically an address. "goto label;" does nothing else than a jump to that address (think about the instruction pointer in assembly). This label stores this RAM address, and that's how you can find out that address.

After you've learned ASM, you'll realize that that address points to a instruction within the .text section of the executable. The .text section is the one which holds you program's (binary) code to be executed.

You can inspect this with:

objdump -x a.out

A practical example

As described in GCC, you can use this to initialize a jump table. Some scanner generators like re2c (see the -g parameter) use that to generate more compact scanners. Maybe there's even a parser generator employing the same technique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜