Returning function pointer type

Viewed 63500

Often I find the need to write functions which return function pointers. Whenever I do, the basic format I use is:

typedef int (*function_type)(int,int);

function_type getFunc()
{
   function_type test;
   test /* = ...*/;
   return test;
}

However this can get cumbersome when dealing with a large number of functions so I would like to not have to declare a typedef for each one (or for each class of functions)

I can remove the typedef and declare the local variable returned in the function as: int (*test)(int a, int b); making the function body look like this:

{
     int (*test)(int a, int b);
     test /* = ...*/;
     return test;
}

but then I do not know what to set for the return type of the function. I have tried:

int(*)(int,int) getFunc()
{
    int (*test)(int a, int b);
    test /* = ...*/;
    return test;
}

but that reports a syntax error. How do I declare the return type for such a function without declaring a typedef for the function pointer. Is it even possible? Also note that I am aware that it seems like it would be cleaner to declare typedefs, for each of the functions, however, I am very careful to structure my code to be as clean and easy to follow as possible. The reason I would like to eliminate the typedefs is that they are often only used to declare the retrieval functions and therefore seem redundant in the code.

8 Answers

Simple example fun function which take void as argument which returns function pointer that function should take int* and int* and returns int*

check the link example using typedef https://www.geeksforgeeks.org/returning-a-function-pointer-from-a-function-in-c-cpp/

#include <stdio.h>

int* fun1(int* y, int* z)
{
    static int var = 0;
    var = (*y + *z);
    printf("Inside fun1 = %d\n", var );
    return &var;
}

int* (*fun())(int*,int*)
{
    printf("Inside fun\n");
    return &fun1;
}

int main()
{
    int a=10,b=20;
    int *ptr = NULL;
    int* (*(*fp)())(int*,int*) = &fun;
    ptr=(*fp())(&a,&b);
    printf("*ptr = %d\n", *ptr );
}
Related