问题
Day after tomorrow is my exam for Computers (JAVA) and I have a big problem in the above title. I understood what does post and pre increment and decrement means. But I can no understand what to do when the matter comes to a complex, long statement. One example for such question is below.
class java_1
{
public void main()
{
int x = 4;
x += x++ - --x + x + x--;
}
}
You see what I meant by complex statements. The statement contains only one variable being incremented and decremented again and again, and I get confused over here. Can you please help me clear my confusion. Also, kindly give the answer to the above code.
回答1:
a += b;
is similar to a = a + b
. Using this assumption we can rewrite
x += x++ - --x + x + x--;
as
x = x + (x++ - --x + x + x--);
Lets now have x = 4
and evaluate right side (from left to right)
x + (x++ - --x + x + x--)
4 + (x++ - --x + x + x--)
^ //still x = 4
4 + (4 - --x + x + x--)
^ //x++ use current value (4), then increment x to 5
4 + (4 - 4 + x + x--)
^ //--x decremented to 4, then use current value (4)
4 + (4 - 4 + 4 + x--)
^ //still x = 4
4 + (4 - 4 + 4 + 4)
^ //x-- read current value (4), then decrement x to 3
So we are getting
x = 4 + (4 - 4 + 4 + 4);
which means
x = 12;
来源:https://stackoverflow.com/questions/29122449/pre-and-post-increment-and-decrement-in-java