Using a Function returning apointer as LValue

不打扰是莪最后的温柔 提交于 2019-12-11 06:04:22

问题


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.


回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/2718695/using-a-function-returning-apointer-as-lvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!