0

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. 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,

storen
  • 955
  • 9
  • 22

2 Answers2

5

It seems that you have misunderstood the difference between lvalue and rvalue. In your case both the expressions a++ and ++a are rvalues and cannot be assigned.

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 =.

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++.

Community
  • 1
  • 1
merlin2011
  • 63,368
  • 37
  • 161
  • 279
-1

the object of operator & is lvalue , an the same is operator ++.but after ++a is done , it returns rvalue , that's the reason wrong.

Nibnat
  • 119
  • 7