Question

I have seen the following phrase from JLS quoted very often:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

However, I do not understand the meaning of "except that E1 is evaluated only once". Under what scenario does "E1" get evaluated twice?

Was it helpful?

Solution

If it had actually been

 E1 = (T)((E1) op (E2))

Expression E1 is interpreted twice -- once on the right to compute the address to read the old value out of, and once on the left when computing the address to store the new value into. If E1 has side effects, they occur each time, and the two addresses may be different. (Though that's generally bad practice, since except for a few specific idioms it tends to badly confuse other humans reading the code -- if you must do it, and it isn't completely obvious what it's doing, be sure to provide comments explaining it!)

But since you wrote

 E1 op= E2

E1 is interpreted only once, to obtain the address from which the old value is read AND to which the new value is written. (Which is what you'd sorta expect since E1 only appears once in the compound assignment expression.) The side effects only occur once, and the address read from and written to are promised to be the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top