-7

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ishaan
  • 43
  • 5
  • 3
    Please read this first: [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask). On the other hand, try it, debug it, and you'll see. BTW no one should use this kind of operations in production code, 'cause no one will ever understand it. – Nagy Vilmos Mar 18 '15 at 12:47
  • 3
    If you learn nothing else from your Computers class, let it be "Don't write code like this". – jas Mar 18 '15 at 12:53
  • Surely the answer to this question is "this code does absolutely nothing detectable". – Andy Turner Mar 18 '15 at 12:55
  • 1
    It's a funny question to check your understanding of operator precedence, but if you ever find something like that in reality, your first fix should be going to your boss and have the guy fired who wrote it. – Florian Schaetz Mar 18 '15 at 12:56
  • How do you evaluate a mathematical expression like "1 + 2 - 3 * 4 + 5 / 6 - 7 - 8 + 9"? – Seelenvirtuose Mar 18 '15 at 13:01

1 Answers1

3

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;
Pshemo
  • 122,468
  • 25
  • 185
  • 269