Reputation: 81
cout<<(x++)++; //fails
cout<<++(++x); //passes
Why does the post increment fail ? I see it happen but not sure of the technical reason.
Upvotes: 7
Views: 764
Reputation: 4247
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.
Upvotes: 4
Reputation: 4031
Exactly. yo cannot perform a ++ over an Rvalue. a good explanation about how rvalue works is given here.
Upvotes: 1
Reputation: 7107
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.
Upvotes: 13