buzhidao buzhidao - 1 year ago 57
C++ Question

why my definition of a function that returns the pointer to another function doesn't work?

I am learning pointer to functions, and want to define a function that has the return value which is the pointer to another function. In my sample program

is trying to return a pointer that points to
. However, the program fails to compile. I have written my thought in the comment, any idea where is the problem?

#include <iostream>

using namespace std;

int next(int );

//define next_fp as a pointer to a function that takes an int and return an int
typedef int (*next_fp)(int);

//define a function that returns a pointer to a function that takes an int and return an int
next_fp fun(next);

int main()

cout << fun(next)(5) <<endl;
return 0;


int next(int n) {
return n+1;

next_fp fun(next) {
//fun's return type is next_fp, which is a pointer to
//a function that take an int and return an int.
return next;

Answer Source
next_fp fun(next);

When declaring a function, you must declare the type of the arguments. Try:

next_fp fun(next_fp next);

// ...

next_fp fun(next_fp next) {
    // ...

As stated in the comments, you should avoid using for a parameter a name already used in the same scope for a function. You may add a trailing _ to mark function parameters (my personal convention, feel free to use yours):

next_fp fun(next_fp next_);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download