7
cout<<(x++)++; //fails 
cout<<++(++x); //passes

Why does the post increment fail ? I see it happen but not sure of the technical reason.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user835194
  • 81
  • 2

3 Answers3

13

x++ returns an rvalue so you can't perform ++ again on it. On the other hand, ++x returns an lvalue so you can perform ++ on it.

Mu Qiao
  • 6,941
  • 1
  • 31
  • 34
  • 1
    also see [this question](http://stackoverflow.com/questions/371503/why-is-i-considered-an-l-value-but-i-is-not) – Benoit Sep 13 '11 at 06:39
4

This is how the increment operators work in C/C++.

If you put the ++ after the variable (postfix increment), the whole expression evaluates to the value of the variable before incrementing.

If you put the ++ before the variable (prefix increment), the expression evaluates to the value after the increment operation.

While the prefix operation returns a reference to the passed variable, the postfix version returns a temporary value, which must not be incremented.

Stephan
  • 4,187
  • 1
  • 21
  • 33
1

Exactly. yo cannot perform a ++ over an Rvalue. a good explanation about how rvalue works is given here.

Stefano
  • 3,981
  • 8
  • 36
  • 66