Asked • 04/24/19

Incrementor logic?

I'm trying to get deeper with post and pre incrementors but am a bit stuck with the following expression : public static void main(String[] args) { int i = 0; i = i+=(++i + (i+=2 + --i) - ++i); // i = 0 + (++i + (i+=2 + --i) - ++i); // i = 0 + (1 + (3 + 2) - 1); // i = 0 + (6 - 1); System.out.println(i); // Prints 0 instead of 5 } I know I'm missing the logic somewhere but where? What I've tried : - Going from left to right (though I know it is not recommended) - Going from the insidest bracket and starting from there. Thanks for the help PS : The comments are the details of my calculus **EDIT 1** I tried to change de hard coded value from the expression from `2` to something else and the result always gives `0` Look at this example : int i = 0; i = i+=(++i + (i+=32500 + --i) - ++i); System.out.println(i); // Prints 0 This expression should logically be nowhere near `0` but somehow it does print it. The same happens when I use a negative : int i = 0; i = i+=(++i + (i+=(-32650) + --i) - ++i); System.out.println(i); // Prints 0 -------------- **EDIT 2** Now, I changed the value of `i` to begin with : int i = 1; i = i+=(++i + (i+=2 + --i) - ++i); System.out.println(i); // Prints 2 i = 2; i = i+=(++i + (i+=10000 + --i) - ++i); System.out.println(i); // Prints 4 i = 3; i = i+=(++i + (i+=(-32650) + --i) - ++i); System.out.println(i); // Prints 6 It gives the double of `i` each time, whatever the hard coded value is.

1 Expert Answer

By:

Hiep L. answered • 04/27/19

Tutor
New to Wyzant

Adjunct Professor at HCC - teaching C++/C#/Java/Python

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.