Pre and Post Increment and Decrement in Java [duplicate]

点点圈 提交于 2019-12-13 10:15:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!