+ 1

x=1 x-=-(++x)-x java is printing out 6, can someone explain this to me? Thanks!

To me it goes like this x=1+2-3 or x=1+2-2 either way I don't get it. How it could come out 6?

12th May 2018, 7:53 PM
noa
2 Respuestas
+ 7
First, it should be noted only a fool would code anything like this. Any time you use a variable with ++ or -- operators and you reuse that variable in the statement, you can not guarantee how the compiler will decide to do things. Tomorrow's compiler update might do things differently breaking your code, x = 1; x -= -(++x)-x; ++x makes x 2 2 -= -2-2 is 2 -= -4 is 6.
12th May 2018, 8:28 PM
John Wells
John Wells - avatar
+ 1
Thanks! it was one of the questions in challenges. I learned two things: - in one line of the code value can't be changed -every side of equation must be added before values change sides
12th May 2018, 8:38 PM
noa