简体   繁体   English

int * p =&a ++和int * p =&++ a

[英]int *p=&a++ and int *p=&++a

The code is simple,I just want to test the priority between & and ++. 代码很简单,我只想测试&和++之间的优先级。

int main()
{
    int a=10;
    int *p;
    int *q;
    p=&++a;//error: lvalue required as unary ‘&’ operand
    q=&a++;//error: lvalue required as unary ‘&’ operand
    return 0;
}

when gcc compile it, two errors came out. gcc编译它时,出现两个错误。 In my opinion, a++ is a right value,but the ++a is a lvalue,so it should not be an error when use & to get it address, 我认为, a++是正确的值,但++a是左值,因此在使用&获取地址时不应有错误,

It seems that you have misunderstood the difference between lvalue and rvalue . 似乎您误解了lvaluervalue之间的区别。 In your case both the expressions a++ and ++a are rvalues and cannot be assigned. 在您的情况下,表达式a++++a均为rvalues ,因此无法分配。

Here is a good description of the distinction, but the quick way to tell whether it is an lvalue is to see whether you get an error if you put it on the left side of an = . 是对区别的一个很好的描述,但是判断它是否是lvalue的快速方法是查看将其放在=的左侧是否出错。

Observe that both of the following two statements produce the same error you describe. 请注意,以下两个语句均会产生与您描述的相同的错误。

++a = 5;
a++ = 6;

Update: As @mafso mentioned below, ++a is indeed an lvalue in the language c++ , and you will not see the error for that expression when compiling with g++ . 更新:如下面@mafso所述, ++a实际上是c++语言中的lvalue ,并且使用g++编译时,您不会看到该表达式的错误。

运算符&的对象是lvalue ,运算符++相同。但是++ a完成后,它返回rvalue ,这就是错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM