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.In the first case subtracting result2 from itself leaves zero which added to x results in x. In the second case adding x to results3 and then subtracting the result from result3 leaves you with -x. Assuming you remember that these results don’t change the value of result2 until all the operations are finished. Choice C wisely uses parenthesis to make the desired order of operations crystal clear. Without the parenthesizes the computer will move from left to right doing the subtraction first. Yet another good example of why you want to use parenthesis. 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.