How can I make a function that returns a function?

When returning a function from another function, the cleanest way to do this is with a typedef:

typedef double (*ftype)(double, double);

Then you can declare your function like this:

ftype OP_PAdd( ftype f, double param3 )
{
    ....
    return f1;
}

You can do this without a typedef, but it’s messy:

double (*OP_PAdd( double (*f)(double,double), double param3 ))(double,double)
{
    return f1;
}

So when you have function pointers as either parameters or return values of other functions, use a typedef.

EDIT:

While you could declare the type like this:

typedef double ftype(double, double);

You can never directly use a type like this in practice. A function can’t return a function (only a pointer to a function), and a variable of this type can’t be assigned to.

Also, you don’t need to explicitly dereference a function pointer to call the function, so the fact that the pointer itself is hidden is not a big issue. It’s also convention to define function pointers as a typedef. From the man page for signal:

   #include <signal.h>

   typedef void (*sighandler_t)(int);

   sighandler_t signal(int signum, sighandler_t handler);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)