shalini_goel14
x=25
x= x++ + x++
It will be taken as
x =(x++) + (++x)
LHS= x
RHS= (x++) + (++x)
...
so final value of x=52.
When i compiled and executed the above code using gcc compiler the final result was x = 53. So i feel the logic described above is not correct.
Also, why should the statement
x = x++ + ++x;
should evaluate to
x = (x++) + (++x);
and not to
x = (x++++) + x;
or
x = x + (++++x);
The reason it does not evaluate to
x = (x++++) + x;
or
x = x + (++++x);
is that in both the case the compiler will throw a error that lvalue is required because it does not have any lvalue on which it can store the result of second '++' operator (the '++' away from x in x++++ or ++++x).
Now why it results in 53 and not 52? I feel below details should answer this.
Before trying to understand the behavior we should have below understanding:
- In case of ++ (pre-increment operator, ++x) in any statement, it always first increment the value and then used the new value in the statement.
- In case of ++ (post-increment operator, x++) the value is first used in the statement and after completion of statement the value is incremented.
So the above statements are evaluated as:
Statement: y = x++ + ++x;
1. x = 25
2. Evaluating pre-increment (++x)
Statement: y = x++ + 26
and x = 26
3. Evaluating post-increment (x++)
Statement: y = 26 + 26
and x = 26 (with x need to be incremented after execution of whole statement)
4. Evaluating addition (+)
Statement: y = 52
and x = 26 (with x need to be incremented after execution of whole statement)
5. Evaluating assignment
y = 52
x = 26 (with x need to be incremented after execution of whole statement)
6. Final values
y = 52
x = 27
Statement: x = x++ + ++x;
1. x = 25
2. Evaluating pre-increment (++x)
Statement: x = x++ + 26
and x = 26
3. Evaluating post-increment (x++)
Statement: x = 26 + 26
and x = 26 (with x need to be incremented after execution of whole statement)
4. Evaluating addition (+)
Statement: x = 52
and x = 26 (with x need to be incremented after execution of whole statement)
5. Evaluating assignment
x = 52 (with x need to be incremented after execution of whole statement)
6. Final values
x = 53
Here we evaluated ++x first and x++ later (i.e., right portion of '+' first and left portion later). This behavior is compiler dependent. While evaluating any binary operator some compilers generate code to evaluate right portion first and some to evaluate left portion first (gcc do to evaluate right portion first). Other compilers may give different result. That's why it is recommended to avoid coding that's compiler dependent. This makes code easily portable.
Let me know if any item need more clarification.
-Pradeep