Attyuttam Saha January 2017
why does if(++x=++y) works and if(x++=++y) does not work?
when i am executing this program:
using namespace std;
it works fine and the output is: Works 9
but if i execute:
using namespace std;
In function 'int main()':
6:11: error: lvalue required as left operand of assignment
BoBTFish January 2017
x++ isn't an lvalue.
x, then returns a
temporary with the original value of
x. A temporary object can't (casts of dubious legality aside) be used on the left hand side of an assignment, so it is not an lvalue.
x and returns a reference to
x (with its new value). You can then assign directly to it if you choose, so it is an lvalue.
However, it is possible you actually meant to compare the two expressions for equality, rather than do an assignment. In which case, you need to use
== rather than
Victor Tran January 2017
x++ returns x, and then increments x. On the other hand, ++x increments x, and then returns it.
The second case makes sense; x is being returned, and you can do whatever. The first case makes no sense at all; x++ isn't a value. In fact, once you get back the value, x is no longer that value.
Joachim Pileborg January 2017
You have to remember that the suffix increment operator returns the
old value, before the increment.
This value is a very temporary value, and as all other temporary values it is not an "lvalue", i.e. it is not something that can be assigned to.
The prefix increment operator does its increment operation, and then return a reference to the new value. For
++x it returns a reference to
is an "lvalue".
The same of course goes for the decrement (
There are many sources all over the Internet that will help you understand the difference between "lvalues" and "rvalues" (temporaries).
salhernandez January 2017
This happens because in the second code snippet you are assigning a value, and not comparing them.
A = B //assigns value B to A
A == B //compares values A and B
Asked in January 2017
Viewed 1,834 times Voted 12 Answered 4 times
Leave an answer
Quote of the day: live life
Devs Planet © all rights reserved