According to operator precedence, the short hand or combined assignment operator is executed the last... So shouldn't the answer be
x+= 4+5;
x=x+4+5;
x=5+4+5; // since the value of x has been changed to 5
If not then please please explain....
Update:But the way we have learnt in our school is .... First do the increment, then the arithmetic, and at last the assignment... Please explain elaborately...
Verified answer
The answer is 13, but many have given the wrong reasoning.
Yes, the combined assignment operator is executed the last, but the value on the left side will remain the same, no matter what happens to x on the right side.
I.e. you'll get 4 + (whatever you get on the right side).
Once the program is done operating with the x++-part, x will increase by one.
So x will be 4 when operating with the x++-part, but will have increased by one by the time you add + x.
In the end, you get 4 + 4 + 5 => 4 + 9 => 13.
x++ does not make x increase after calculating everything else. It makes x increase right after it's done operating with the x++-part.
Example:
x += x++ +x gives you 13 if x is initially 4.
x += x++ +y gives you 12 if x and y are initially 4.
Note:
x++ means increment after operating with the x++-part.
++x means increment before operating with the ++x-part.
So x += ++x +x would be: 4 + 5 + 5 => 4 + 10 => 14
(The only difference is that the middle value would be 5 instead of 4.)
Answer = 13
x+=(x++) +x;
You do everything on the right hand side of the "=" sign first, with the ++being executed with higher priority, so x+=(x++) +x;
x+= (5) +x
x+= (5) + 4
x = x + (5) + 4
= 4 + 5 + 4
= 13
__
Click here for a sample run and check the output for yourself: http://ideone.com/IJmeE
First right hand side is solved and also increment operator will be executed at last so will be ignored
So output in 1st step will be : x+ = 4 + 4
So final value of x will be 12
x += x++ + x;
You're looking at 13. X will be incremented after the line of code has been processed.
x = 4 + 4 + 4; This gives us 12, then x will be incremented, leaving a final answer of 13.
first expression is evaluated and then x value be modified (incremented) by once number of postfix incremenet operators are 1. While evaluating current value of x is used.
x += 4+ 4 is evaluated. Thus, x value becomes 12.
After evaluating the expression x is incremented by 1. Thus, x values becomes 13 after this expression.
x?