How typedef works for function pointers

后端 未结 4 1127
名媛妹妹
名媛妹妹 2020-11-29 07:54

I think I may be suffering from the dreaded \"accidental programmer\" disease, at least when it comes to typedefs and function pointers. So I\'ve been experimenting with all

4条回答
  •  囚心锁ツ
    2020-11-29 08:30

    The address of a function name and the plain function name both mean the same thing, so & has no effect on a function name.

    Similarly, when using function pointers, multiple dereferencing isn't a problem:

    #include 
    typedef void print(void);
    static void dosomething(void) { printf("Hello World\n"); }
    
    int main(void)
    {
        print *f1 = dosomething;
        print *f2 = &dosomething;
        f2();
        (f1)();
        (*f1)();
        (**f2)();
        (***f1)();
        (****f2)();
        (*****f1)();
    }
    

    That compiles cleanly under:

    gcc -O3 -g -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
        -Wold-style-definition -std=c99 xx.c -o xx
    

    I would not claim that multiple stars is good style; it isn't. It is 'odd, and (yes, you may say it) perverse'. One is sufficient (and the one star is mainly for people like me who learned to program in C before the standard said "it is OK to call a function via a pointer without using the (*pointer_to_function)(arg1, arg2) notation; you can just write pointer_to_function(arg1, arg2) if you like"). Yes, it is weird. No, no other type (or class of types) exhibits the same behaviour, thank goodness.

提交回复
热议问题