Partha Bera
Partha Bera

Reputation: 458

Weird experience with C++ preIncrement and postIncrement

++a = b operation is showing no error but a++ = b is showing error while compiling with g++. Both the variable are initialized before these operations.

Although these operation have no practical usage I think both of them should issue the same error while compiling. What do you think? If there is a valid reason kindly explain to me. Thanks in advance! :)

P.S. gcc gives error on both of these.

Upvotes: 3

Views: 305

Answers (4)

SingerOfTheFall
SingerOfTheFall

Reputation: 29976

The result if ++a is an Lvalue, but the result of a++ is an Rvalue, you can't assign anything to an Rvalue, hence the error.

The difference is that (simplifying a bit) an Lvalue is an expression that refers to some object, while an Rvalue refers to the data stored somewhere in the memory.

Let's say the result of a++ is 7. Basically, when you write a++ = b; you are trying to assign b to 7 which is clearly not possible. When you write ++a = b;, on the other hand, the result of the increment is an Lvalue that refers to a, so the assignment will be valid.

You can read more about Lvalues and Rvalues here.

Upvotes: 6

cadaver
cadaver

Reputation: 265

Let see how declarations of pre/post-increment look like ( http://en.cppreference.com/w/cpp/language/operator_incdec ):

++a: T& operator ++(T& a);
a++: T operator ++(T& a, int);

And you've got the answer - preInc returns reference, so you can override "a" variable using "=" operator.

Upvotes: 8

Luchian Grigore
Luchian Grigore

Reputation: 258628

++a is an l-value (increments a and "returns" the new value), a++ is an r-value (increments a and "returns" a temporary with the old value of a).

Upvotes: 3

Tobias Ritzau
Tobias Ritzau

Reputation: 3327

As you say it is not code that makes much sense, but I would say that ++a increments a and yields the value of the incremented variable, while a++ yields the lvalue of the variable and then increments a (which is then overwritten by the assignment). You can not assign to the value of a, you need an lvalue (which is basically a value that has an associated memory allocated).

Upvotes: 1

Related Questions