What does a && operator do when there is no left side in C?

后端 未结 3 738
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 01:22

I saw a program in C that had code like the following:

static void *arr[1]  = {&& varOne,&& varTwo,&& varThree};

varOne: printf(\"On         


        
3条回答
  •  悲哀的现实
    2020-12-29 01:58

    It's a gcc-specific extension, a unary && operator that can be applied to a label name, yielding its address as a void* value.

    As part of the extension, goto *ptr; is allowed where ptr is an expression of type void*.

    It's documented here in the gcc manual.

    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 statement, goto *exp;. For example,

    goto *ptr;
    

    Any expression of type void * is allowed.

    As zwol points out in a comment, gcc uses && rather than the more obvious & because a label and an object with the same name can be visible simultaneously, making &foo potentially ambiguous if & means "address of label". Label names occupy their own namespace (not in the C++ sense), and can appear only in specific contexts: defined by a labeled-statement, as the target of a goto statement, or, for gcc, as the operand of unary &&.

提交回复
热议问题