Why after executing such a code
int a = 0; a += a++;
Does a
write 0
, not 1
?
Expression
a += a++;
by definition, the +=
operator +=
equivalent to
a = a + a++;
In Java, the calculation of such expressions and the moments of occurrence of side effects of operators are uniquely ordered. Operands of binary operators are calculated from left to right:
a + a++
.a
. The value of a
at this moment is 0
. So the value of the left operand is 0
.a++
. The value of a
at this moment is 0
and when calculating a++
value of a
increases by 1. However, the result of the postfix increment is by definition the initial value of a
, that is, 0
.+
calculated, that is, the whole sub-expression a + a++
. It gives the result 0
( 0 + 0
). Notice that at this point, the variable a
already has the value 1, obtained in step 4.0
, is entered into the variable a
. This is the final value of a
.Thus, formally, the variable a
for some instant "managed" to get the value 1
at step 4, but then its value was again returned to 0
by the assignment operator at step 6
Note that if the expression a = a + a++
eventually puts 0
into a
, the expression a = a++ + a
will put a into 1
.
We read the specification: jls-15.14.2 :
The value of the variable is the value of the variable before the new value is stored.
We read about priorities .
The result: first, a++
calculated in a itself is now 1
, but the result of the increment operation itself will be the original value of a
, i.e. 0
; as a result, the expression reduces to a += 0;
and in a
will be 0
.
++
has a higher priority than +=
, the left part +=
in this example will be calculated before ++
. The link to jls-15.14.2 contains valid inofrmatsiyu. - AnT+= ++
transformed into = + ++
, so I didn’t write about it. - Suvitruf ♦ pmSource: https://ru.stackoverflow.com/questions/949801/
All Articles
=
and+=
differ significantly in behavior in order to consider the behavior of these examples separately. - AnT pm