Search code examples
c++cincrementdecrement

Mixing post- and pre- increment/decrement operators on the same variable


Possible Duplicate:
Why is ++i considered an l-value, but i++ is not?

In C++ (and also in C), if I write:

++x--
++(x--)

i get the error: lvalue required as increment operand

However (++x)-- compiles. I am confused.


Solution

  • Post- and pre-increment operators only work on lvalues.

    When you call ++i the value of i is incremented and then i is returned. In C++ the return value is the variable and is an lvalue.

    When you call i++ (or i--) the return value is the value of i before it was incremented. This is a copy of the old value and doesn't correspond to the variable i so it cannot be used as an lvalue.

    Anyway don't do this, even if it compiles.