I was studying signal handling in unix and came across this
void (*signal(int sig, void (*func)(int)))(int);
I dont understand this prototype and how this returns a pointer to a function.
I also read this answer: How do function pointers in C work? but it's not clear to me.
It's supposed to return a function pointer but I dont understand where it specifies the return type as another function pointer.
The way I see it is that, if I use (*foo(int n)) in a function definition the return type of this function foo(int n) becomes a function pointer.Is this correct?
Is there a simpler example for this?
So, let's look at how a function pointer is declared.
return-type (*function-name)(parameter-list);
In the declaration you posted, there are two function-pointer types in play. The first is a parameter that's passed into a function that matches the signal prototype:
void (*signal(int sig, void (*func)(int)))(int);
// ^^^^^^^^^^^^^^^^^
Let's rename that function pointer type to handler and give it its own declaration.
typedef void (*handler)(int);
void (*signal(int sig, handler func))(int);
Now we can break down the rest of the declaration. The "inside" part is the actual function declaration:
...signal(int sig, handler func)...
And the "outside" describes the function pointer it returns:
void (...)(int);
This is also the same function-pointer type as our handler type, so with that typedef in place, we could redeclare the signal function like this:
handler signal(int sig, handler func);
(Much prettier.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With