Reputation:
Please explain me why the code below doesn't work
#include <stdio.h>
int foo() { return 1; }
int bar() { return 2; }
void ass()
{
foo=bar;
}
int main()
{
ass()
}
The following error
test.cpp: In function ‘void ass()’: test.cpp:8:8: error: assignment of function ‘int foo()’ test.cpp:8:8: error: cannot convert ‘int()’ to ‘int()’ in assignment
caused.
Upvotes: 0
Views: 1022
Reputation: 1467
try this:
typedef int (*int_funcptr_void)(void);
then, you can simply:
int foo() { return 1; }
int bar() { return 2; }
int_funcptr_void func;
void ass()
{
func = (int_funcptr_void)foo;
}
int main()
{
ass(); //you also forgot a semicolon here, but nice naming
//then, we can call it:
printf("%d\n", func());
}
and get this:
hydrogen:tmp phyrrus9$ ./a.out
1
Hope that helps.
Upvotes: 1
Reputation: 7625
You can not assign function
to function
, as you can not assign int
to int
. Think naturally, you assign an int variable to another int variable, which means you are assigning rvalue of the second variable to the lvalue(address) of the first one. Same rule for function, you can assign a function object to another function object. The difference is, function is code, not data, but it has an address ( the starting point). So assigning function to one another generally means assigning the address of the function to a variable which can hold an address, i.e. a function pointer.
void f(){}
typedef void(*pF)(); //typedef for easy use
pf foo; //create a function pointer object
foo = &f; //assign it the address of the function
Upvotes: 0
Reputation: 7400
You must use a function pointer. You cannot assign to the function itself.
int(*baz)() = &foo;
baz();
Upvotes: 3