Recently someone posted the following question and bit of code to the Advanced Placement Computer Science teacher mailing list:
Assuming that all values are ints that have been properly initialized, which two of the following three lines of code are equivalent?
This is a simple (well reasonably simple) question of precedence. The tricky part for most students is the first statement which includes –= . Tricky because a) it is easy to miss (I did on first reading) and b) people often either forget where that fits in the order of precedence or think that it doesn’t matter. OK probably solid professionals don’t mess this up but for beginners it is a landmine.
Choices B and C are pretty straight forward. It doesn’t matter (in B) if you add x to result2 before you subtract the result from the original result2 or if you subtract result2 from result2 leaving zero before adding x. Either way you get x as your final result2. Assuming you remember that these results don’t change the value of result2 until all the operations are finished. Choice C wisely uses parenthesizes to make the desired order of operations crystal clear. Which brings us back to choice A.
The –= has a lower precedence than the +. Remember that? Ok then realize that result1 + x does not change the value of result1 immediately. Rather it is held and then subtracted from result1 (its original value) before being reset to the result of this final operation. So choice A and C return the same result. Great!
The problem in my mind is that choice A is just too darn clever. Nothing of value is saved by not doing tings the way choice C is done. No operations are removed. Not registers are being saved. No extra value at all really. But it does add to the possible confusion and make understanding the program harder. The positives would have to really outweigh the negatives to make choice A a good implementation choice. Showing everyone how clever you are is not a positive BTW.