且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法理解错误条件WRT左值

更新时间:2023-02-01 19:03:44

a ++ 递增您的 a 并返回 old a & 运算符返回变量的地址。但是返回的 old a 没有地址。这是非常临时的事情,而不是左值。这就是为什么您不能使用它的地址。


I am a beginner in programming and was trying out some combinations.

#include<stdio.h>


int main()
{
int a=5;

printf("%d",&a); // STATEMENT 1
printf("\n%d",a); //STATEMENT 2
printf("\n%d",&(a++)); //STATEMENT 3
printf("\n%d",a);  //STATEMENT 4

return 0;
}

I get a error in STATEMENT 3 saying

[Error] lvalue required as unary '&' operand

I expected the output of STATEMENT 1 & 3 to be same as both address are the same.

Also I expected the output of STATEMENT 2 to be 5 & STATEMENT 4 to be 6.

I looked up and found a similar question : Lvalue required error

I understood the issue in that question.From the comments to the first answer to above mentioned question I see lvalue as something to which something can be stored.

But I still can't understand why &(a++) or &(++a) should give an error. Any help will be appreciated.

Thank You for reading this.

[Edit] Thank you for answering. If possible please include references where the exact sequence of execution or nature of such expressions are discussed. That way rookies like me won't trouble the community with such trivial questions.

a++ increments your a and returns the old value of a. The & operator returns the address of a variable. But the returned old value of a doesn't have an address. It's a very temporary thing, not an lvalue. That's why you can not take the address of it.