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 prior and came up with an answer, 15. The instructor, however, came up with an answer of 20. But then he ran that Java program and was surprised when it came up with my answer (which I had not shared with him at the time, but shared with him afterwards via email).
It turns out that while there is a standard way specified to evaluate that expression when humans read it, the code that the compiler generates to evaluate it is implementation dependent and those implementation dependencies can change the results unexpectedly. And as my tests revealed, different languages and different types of computers will indeed generate different results, albeit in two different ways in this case. 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. There can be a tendency to pack as much as you can in one line of code, especially in C/C++, but doing so could expose you to situations like this.
During the week after that class, 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 2020 January 19