'cannot convert int (*(int))(int) to int (*(int))(int)
i'm trying to learn about function that returning a pointer to a function, after i tried to compile the code, it gives me this kind of error:
cannot convert
int (*(int))(int)
toint (*(int))(int)
in assignment.
I know those two int (*(int))(int)
is the same thing, but why this error happens?
I'm using g++ to compile this code
int sum(int i){
return i+i;
}
int (*fp)(int) = sum;
int (*someFunc(int))(int a){
return fp;
}
int main(){
int i = 1;
int (*fp2(int))(int);
fp2 = someFunc;
return 0;
}
I expect the fp2 will be a pointer to the fp variable, but it just giving me some error.
Any helps is appreciated, thank you
Solution 1:[1]
You defined fp2
as a function itself, not a pointer to a function, meaning you can't assign to it. You need to make it a pointer to a function:
int (*(*fp2)(int))(int);
fp2 = someFunc;
Better yet, use typedef
so the code isn't super confusing:
typedef int func1(int);
typedef func1 *func2(int);
int sum(int i) {
return i+i;
}
func1 *fp = sum;
func1 *someFunc(int a) {
return fp;
}
int main() {
int i = 1;
func2 *fp2 = someFunc;
return 0;
}
Solution 2:[2]
It seems you mean the following
int (*( *fp2 ) (int))(int);
fp2 = someFunc;
that is fp2 should be declared as a pointer to function. Otherwise you are trying to apply the assignment operator to a function.
You could make the declarations simpler by introducing an alias.
For example
int sum(int i){
return i+i;
}
using Fp = int( * )( int );
Fp fp = sum;
Fp someFunc(int){
return fp;
}
int main()
{
Fp ( *fp2 ) (int);
fp2 = someFunc;
return 0;
}
Solution 3:[3]
It took me awhile to sort out the issues concerning function pointers, but I recommend the rules below: (a) Use a typedef
statement for any user-defined storage class that allows each type to be treated as a single thing (e.g., typedef struct _mystruct_ MyStruct;
). Following this shortcut makes possible: (b) Each part of the three-part expression (e.g., RETURN-TYPE (POINTER-DECLARATION)(LIST-OF-ARGUMENT-TYPES);
) should contain one set of parentheses except for the leftmost term which contains no parentheses, and the middle term of the expression is the name of the variable (and therefore containers the asterisk[*
]) for instance, int (*_mainPtr)(int, const char *[]);
should define a pointer to the main
function in your program.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kevin |
Solution 2 | Vlad from Moscow |
Solution 3 | C. R. Ward |