Evaluating (x + x * ++x)
One night in Java class, the instructor wanted to demonstrate the trouble that can be caused by referencing a variable more than once in an expression that pre/post-increments/decrements it:
x = 3; y = x + x * ++x; System.out.println("x = "+x+"; x + x * ++x = "+y+"\n");
Having always had the good sense to not try something like that, I simply applied the evaluation theory I had learned a couple decades back and came up with an answer, 15. The instructor, however, came up with an answer of 20. Then he ran that Java program and was surprised when it came up with my answer (which I had not shared with him.
It turns out that there's no specified way in the standard to evaluate that expression and, as my tests revealed, different languages and different types of computers will generate different results. The bottom line and basic lesson from this test is: don't use the same variable more than once in an expression where you increment or decrement it.
But I got to wondering about it so I wrote test programs in every language I had access to. I compiled my results and came to realize that the value of y depended very much on how the intermediate values of x were stored and retrieved. An assembly listing of the C code and reference to the Java virtual-machine specification confirmed my suspicions.
So I wrote up my results as posted below.
Return to Top of Page
Return to My Programming Home Page
Share and enjoy!
First uploaded on 2008 February 08.
Updated 2011 July 18