Engineer's Asylum

Can a function appear on left side of assignment operator in C++?

Hello guys,
I came across this code snippet in which function was found on the left side of the assignment operator. The code is attached hereby. The program doesn’t give a compilation error and works fine. What can be the reason behind? Is this applicable only in C++?

#include< iostream>

using namespace std;
int x = 5;

int   &f() {
  return x;
}

main () {
  f() = 10;
  cout<<x;
}

Yes, there is nothing wrong with a function on the left side of the assignment operator in C++. you can do this in C++ if the function returns a reference, as a reference is an lvalue.

You can’t assign directly to the return value of a function in C since it is not an lvalue. However in C language, if the function returns a pointer you can dereference it. This will give you an lvalue and you can assign to it. The below code is for C language.

int value = 0;
int *getvalue()
{
    return &value;
}

int main()
{
    printf("valuel=%d\n", value);    // prints 0
    *getvalue() = 200;
    printf("value=%d\n", value);    // prints 200
}