Reputation: 4764
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 fun
is trying to return a pointer that points to next
. 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;
}
Upvotes: 1
Views: 54
Reputation: 172864
Parameter is not declared properly in function declaration next_fp fun(next);
(and definition); next
is not a type, it's a name of function.
You should change it to:
next_fp fun(next_fp);
and for definition:
next_fp fun(next_fp 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;
}
Upvotes: 1
Reputation: 2004
This works for me:
#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_fp);
int main()
{
return 0;
cout << (fun(next))(5) <<endl;
}
int next(int n) {
return n+1;
}
next_fp fun(next_fp www) {
//fun's return type is next_fp, which is a pointer to
//a function that take an int and return an int.
return www;
}
Upvotes: 0
Reputation: 15956
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_);
Upvotes: 1