Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function pointer to return a function pointer? [duplicate]

Tags:

c

pointers

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?

like image 518
rs911 Avatar asked Jun 15 '26 05:06

rs911


1 Answers

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.)

like image 76
Adam Maras Avatar answered Jun 17 '26 20:06

Adam Maras