Reputation: 1920
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;
}
While I can use a pointer variable as a lvalue, why can't I use a function returning a pointer as a lvalue?
Also, when the function returns a refernce, instead of a pointer, then it becomes a valid lvalue.
Upvotes: 2
Views: 460
Reputation: 5148
Please recheck the last statement of main() in second code snippet. Lvalues are variables that can be used to the left of the assignment operator (=). You're in effect assigning value x to a function instead of the other way round. A function may take arguments or return values. You cannot directly assign them a value.
Upvotes: 0
Reputation: 34537
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);
}
Upvotes: 1