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

2020-05-28 11:46发布

问题:

Please explain this type signature : void (*signal(int signo, void *(func)(int)))(int)

回答1:

The type signature of the signal function is a bit more clear when a typedef is used for the function pointers that are passed around:

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

sighandler_t is a pointer to a function that takes an int parameter and returns nothing. The signal function takes such a function pointer as its second parameter. It also returns a function pointer of that type.



回答2:

C declarations need to be read from the inside out. The tricky part with complex function declarations is figuring out which is the innermost declarator (where to start). Its generally the first identifier that is not a type identifier. So in this case:

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

the declarator is signal. Within the parenthesis, suffixes are higher precedence than prefixes, so signal is a function taking two args (the (int signo, void *(func)(int)) part), that returns a pointer (the prefix *) to a function taking a single int arg (the (int) on the end), and returning void