Aditi Roychoudhury wrote:Thanks for the reply.
I had the understanding that the post-increment/decrement operators are evaluated only after the complete expression is evaluated and the value is returned.
Can someone please confirm this?
Thanks,
Aditi.
Aditi,
These are the fundamental rules regarding expressions with binary operators:
- Each operand in a binary operator must be fully evaluated before the operator acts on the operands.
- Operators are evaluated left to right (first the left operator, then the second operator.)
In your case, you have this:
x = x++ + x--;
You have quite a bit going on here, despite the apparent simplicity:
- An assignment operator.
- A numeric addition operator.
- A postincrement operator.
- A postdecrement operator.
The way this is evaluated is:
Before the assignment can take place, both the LHS (x) and the RHS (x++ + x--) must be evaluated.
For the RHS itself: both x++ and x-- must be evaluated before the addition can take place.
So x++ is evaluated (changes value of x to 46 and evaluates to 45,) x-- is evaluated (changes value of x to 45 and evaluates to 46,) and then the addition is performed (45 + 46, which equals 91.)
Then 91 is assigned to the variable x (the evaluation of the LHS of the assignment operator.
Analyzing it this way might seem overkill, but if you are systematic you will be able to reach sounder conclusions, especially with expressions that contain side effects like this one (or even more complex expressions.)