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
Related videos on Youtube
Lucas
Updated on October 23, 2020Comments
-
Lucas over 3 years
I've misplaced
+=
with=+
one too many times, and I think I keep forgetting because I don't know the difference between these two, only that one gives me the value I expect it to, and the other does not.Why is this?
-
Atreys over 12 years+1 for "don't use this" If used intentionally, the intent is probably to confuse. If used unintentionally, it is a bug.
-
deadcode about 6 yearsHelpful and concise answer but, forgive me for being new, what is meant by unary
+
of b? Isn'ta = b
same asa =+ b
according to this? -
dlev about 6 years@deadcode Yes! The unary
+
isn't the "make operand positive" operator, it's actually the "identity" operator. It's... not that helpful :) -
SunnyAk almost 4 yearsThe way
a = +b
works is as follows:int b = -5;
Variable a is now set to a unary of b when we writea = +b;
So,a = + (-5)
, resulting ina=-5