I have this program and I'm getting:
lvalue required as left operand of assignment
because of the line function_a = function
.
int function_a(int j){
return j+10;
}
int function_b(int j){
return j;
}
void set_a(int (*function)(int)){
function_a = function;
}
int main(){
int a = function_a(2);
printf("%d, ", a);
set_a(function_b);
int b = function_a(2);
printf("%d", b);
}
I want to set function_a
to function_b
in function set_a
. So I'm expecting output 12, 2
. What I should do to assign this properly?
A function definition cannot be replaced by assignment, ie a function definition is not an lvalue to which you can assign something, and that's why you get the error; But you can define a function pointer and assign different function definitions, and call the function pointer just as if it were a function in the sense of an ordinary function definition:
int function_a(int j){
return j+10;
}
int function_b(int j){
return j;
}
int (*f)(int) = function_a;
void set_a(int (*function)(int)){
f = function;
}
int main(int argc, const char *argv[])
{
int a = f(2);
printf("%d, ", a);
set_a(function_b);
int b = f(2);
printf("%d", b);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.