How to declare a function that returns a pointer to a function?

Imagine the myFunctionA function with the double and int parameters:

myFunctionA (double, int); 

This function should return a function pointer:

 char (*myPointer)(); 

How to declare this function in C?

+4
source share
4 answers
 void (*fun(double, int))(); 

According to the right-left rule, fun is a double, int function that returns a pointer to a function with undefined parameters, returning void .

EDIT: This is another reference to this rule.

EDIT 2: This version is intended only for compactness and in order to show that it really can be done.

It is really useful to use typedef here. But not to the pointer, but to the type of function itself .

Why? Because you can use it as a kind of prototype, and so make sure that the functions really match. And since the identifier as a pointer remains visible.

So a good solution would be

 typedef char specialfunc(); specialfunc * myFunction( double, int ); specialfunc specfunc1; // this ensures that the next function remains untampered char specfunc1() { return 'A'; } specialfunc specfunc2; // this ensures that the next function remains untampered // here I obediently changed char to int -> compiler throws error thanks to the line above. int specfunc2() { return 'B'; } specialfunc * myFunction( double value, int threshold) { if (value > threshold) { return specfunc1; } else { return specfunc2; } } 
+4
source

typedef is your friend:

 typedef char (*func_ptr_type)(); func_ptr_type myFunction( double, int ); 
+12
source

Make typedef:

 typedef int (*intfunc)(void); int hello(void) { return 1; } intfunc hello_generator(void) { return hello; } int main(void) { intfunc h = hello_generator(); return h(); } 
+3
source
 char * func() { return 's'; } typedef char(*myPointer)(); myPointer myFunctionA (double, int){ /*Implementation*/ return &func; } 
0
source

Source: https://habr.com/ru/post/1379890/


All Articles