Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to write a function that returns a function pointer. 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 I am not allowed to return a function pointer?

like image 735
Andy Balaam Avatar asked Sep 12 '13 20:09

Andy Balaam


1 Answers

You are allowed to return a function pointer, and the correct syntax looks like this:

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

Complete 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
}

Which compiles and runs like this:

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

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

like image 197
Andy Balaam Avatar answered Sep 25 '22 20:09

Andy Balaam