Search code examples
functionpointerslvalue

Using a Function returning apointer as LValue


Why cant I used a function returning a pointer as a lvalue?

For example this one works

int* function()
{
    int* x;
    return x;
}

int main()
{
    int* x = function();
    x = new int(9);
}

but not this

int* function()
{
    int* x;
    return x;
}

int main()
{
   int* x;
   function() = x;
}
  1. While I can use a pointer variable as a lvalue, why can't I use a function returning a pointer as a lvalue?

  2. Also, when the function returns a refernce, instead of a pointer, then it becomes a valid lvalue.


Solution

  • Your first sample doesn't do why I think you think it does. You first store the result of the function call in the variable x and then you override x's value with the newly created array. *(function()) = 5 should properly try to write 5 to some random memory location specified by the local variable x inside your function.

    Sample:

    int x;
    
    int* function()
    {
        return &x;
    }
    
    int main()
    {
       *(function()) = 5;
       printf("%d\n", x);
    }