The difference between += and =+
Solution 1:
a += b
is short-hand for a = a + b
(though note that the expression a
will only be evaluated once.)
a =+ b
is a = (+b)
, i.e. assigning the unary +
of b
to a
.
Examples:
int a = 15;
int b = -5;
a += b; // a is now 10
a =+ b; // a is now -5
Solution 2:
+=
is a compound assignment operator - it adds the RHS operand to the existing value of the LHS operand.
=+
is just the assignment operator followed by the unary + operator. It sets the value of the LHS operand to the value of the RHS operand:
int x = 10;
x += 10; // x = x + 10; i.e. x = 20
x =+ 5; // Equivalent to x = +5, so x = 5.
Solution 3:
+=
→ Add the right side to the left
=+
→ Don't use this. Set the left to the right side.
Solution 4:
a += b
equals a = a + b
. a =+ b
equals a = (+b)
.
Solution 5:
x += y
is the same as
x = x + y
and
x =+ y
is wrong but could be interpreted as
x = 0 + y