How to understand this define

前端 未结 6 2476
-上瘾入骨i
-上瘾入骨i 2021-02-19 23:19

Nowadays , i was reading the APUE.and i found the function defined as below:

void (*signal(int signo, void (*func)(int)))(int);

i was confused,

6条回答
  •  我寻月下人不归
    2021-02-20 00:00

    void (*signal(int signo, void (*func)(int)))(int);
    

    signal is function that takes int and a pointer to function taking int and returning void and returns a function pointer taking int and returning void. That is,

    typedef void(*funcPtr)(int)
    

    then we have

    funcPtr signal(int signo, funcPtr func); //equivalent to the above
    

    The syntax is indeed strange, and such things better be done with a typedef. As an example, if you want to declare a function that takes an int and returns a pointer to a function taking char and returning double will be

    double (*f(int))(char);
    

    Edit: after a comment that reads "Wooooooow", I am providing another example which is more "woooow" :)

    Let's declare a function that takes
    1. a pointer to array of 5 pointers to functions each taking float and returning double.
    2. a pointer to array of 3 ponters to arrays of 4 ints
    and returns a pointer to function that takes a pointer to function taking int and returning a pointer to function taking float and returning void and returns unsigned int.

    The typedef solution would be this:

    typedef double (*f1ptr) (float);
    typedef f1ptr (*arr1ptr)[5];
    typedef int (*arr2ptr)[4];
    typedef arr2ptr (*arr3ptr)[3];
    typedef void(*f2Ptr)(float);
    typedef f2ptr (*f3ptr)(int);
    typedef unsigned int (*f4ptr) (f3ptr);
    f4ptr TheFunction(arr1ptr arg1, arr3ptr arg2);
    

    Now, the funny part :) Without typedefs this will be:

     unsigned int (*TheFunction( double (*(*)[5])(float), int(*(*)[3])[4]))( void(*(*)(int))(float))
    

    My god, did I just write that? :)

提交回复
热议问题