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

后端 未结 3 741
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    This is a gcc extension, known as "Labels as Values". Link to gcc documentation.

    In this extension, && is a unary operator that can be applied to a label. The result is a value of type void *. This value may later be dereferenced in a goto statement to cause execution to jump to that label. Also, pointer arithmetic is permitted on this value.

    The label must be in the same function; or in an enclosing function in case the code is also using the gcc extension of "nested functions".

    Here is a sample program where the feature is used to implement a state machine:

    #include 
    #include 
    #include 
    
    int main(void)
    {
        void *tab[] = { &&foo, &&bar, &&qux };
    
        // Alternative method
        //ptrdiff_t otab[] = { &&foo - &&foo, &&bar - &&foo, &&qux - &&foo };
    
        int i, state = 0;
    
        srand(time(NULL));
    
        for (i = 0; i < 10; ++i)
        {
            goto *tab[state];
    
            //goto *(&&foo + otab[state]);
    
        foo:
            printf("Foo\n");
            state = 2;
            continue;
        bar:
            printf("Bar\n");
            state = 0;
            continue;
        qux:
            printf("Qux\n");
            state = rand() % 3;
            continue;
        }
    }
    

    Compiling and execution:

    $ gcc -o x x.c && ./x
    Foo
    Qux
    Foo
    Qux
    Bar
    Foo
    Qux
    Qux
    Bar
    Foo
    

提交回复
热议问题