What does "error: myfn declared as a function returning a function" mean?

I am trying to write a function that returns a pointer to a function. Here is my minimal example:

void (*myfn)(int)() // Doesn't work: supposed to be a function called myfn { // that returns a pointer to a function returning void } // and taking an int argument. 

When I compile this with g++ myfn.cpp , it prints this error:

 myfn.cpp:1:19: error: 'myfn' declared as function returning a function myfn.cpp:1:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default] 

Does this mean that I am not allowed to return a pointer to a function?

+6
source share
1 answer

You are allowed to return a function pointer, and the correct syntax is as follows:

 void (*myfn())(int) { } 

Full example:

 #include <cstdio> void retfn(int) { printf( "retfn\n" ); } void (*callfn())(int) { printf( "callfn\n" ); return retfn; } int main() { callfn()(1); // Get back retfn and call it immediately } 

What compiles and runs as follows:

 $ g++ myfn.cpp && ./a.out callfn retfn 

If anyone has a good explanation why the g ++ error message suggests this is not possible, I would be interested to hear it.

+7
source

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


All Articles