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.
You cannot return a function in C - you return a pointer to a function. If you mean to define a function which returns a pointer to a function which again returns a pointer to a function and so on, then you can use typedef to implement it.
You need to use the new keyword instead to create new Foo on the heap. The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory.
C++ allows you to return a pointer to this array, but it is undefined behavior to use the memory pointed to by this pointer outside of its local scope.
int (*getFunc())(int, int) { … }
That provides the declaration you requested. Additionally, as ola1olsson notes, it would be good to insert void
:
int (*getFunc(void))(int, int) { … }
This says that getFunc
may not take any parameters, which can help avoid errors such as somebody inadvertently writing getFunc(x, y)
instead of getFunc()(x, y)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With