Confusion about an error: lvalue required as unary '&' operand [duplicate]

百般思念 提交于 2019-12-01 06:03:53

There is a difference between C and C++ relative to the prefix increment operator ++.

In C the result is the new value of the operand after incrementation. So in this expression &(++num) there is an atttempt to get the address of a temporary object (rvalue).

In C++ the program will be correct because in C++ the result is the updated operand; it is an lvalue.

That is in C the result is a new value while in C++ the result is the updated operand.

So in C you may not for example write

++++++x;

while in C++ this expression

++++++x;

is correct and you may apply the unary operator & to the expression like

&++++++x;

To make the function correct in C you have to separate the applied operators like

int *foo(void) {
    static int num = 1;
    ++num;
    //return &(++num);
    ++num;
    return #

}

The result of ++num is the new value, not the variable, so you're trying to take the address of something that is not actually stored anywhere. That's the layman's explanation.

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