Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for a pointer to a function returning a function pointer in C

How to declare a pointer to a function returning another function pointer? Please share with me the syntax and an example code snippet.

Also, in which scenario would a function pointer returning a function pointer be used?

like image 925
vijayanand1231 Avatar asked Jan 04 '12 06:01

vijayanand1231


2 Answers

This is trivial with typedefs:

typedef int(*FP0)(void);
typedef FP0(*FP1)(void);

FP1 is the type of a pointer to a function that returns a function pointer of type FP0.

As for when this is useful, well, it is useful if you have a function that returns a function pointer and you need to obtain or store a pointer to this function.

like image 167
James McNellis Avatar answered Sep 21 '22 01:09

James McNellis


If you avoid using typedef, it is hard. For example, consider signal() from the C standard:

extern void (*signal(int, void (*)(int)))(int);

void handler(int signum)
{
    ...
}

if (signal(SIGINT, SIG_IGN) != SIG_IGN)
    signal(SIGINT, handler);

Using typedefs, it is easier:

typedef void Handler(int);
extern Handler *signal(int, Handler *);

void handler(int signum)
{
    ...
}

if (signal(SIGINT, SIG_IGN) != SIG_IGN)
    signal(SIGINT, handler);

Note that for the signal() function, you would normally simply use <signal.h> and let the system worry about declaring it.

like image 44
Jonathan Leffler Avatar answered Sep 21 '22 01:09

Jonathan Leffler