3

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?

2
  • 1
    What have you done so far in attempting to solve your problem? Commented Apr 4, 2017 at 22:00
  • 1
    @narusin damn, it won't let me downvote the comment :-( Commented Apr 4, 2017 at 22:11

1 Answer 1

7

A function definition cannot be replaced by assignment, i.e. 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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.