user835194
user835194

Reputation: 81

Post increment operator ++

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

Answers (3)

Stephan
Stephan

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

Stefano
Stefano

Reputation: 4031

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

Upvotes: 1

Mu Qiao
Mu Qiao

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

Related Questions