user773737
user773737

Reputation:

The difference between += and =+

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?

Upvotes: 53

Views: 126688

Answers (8)

dascandy
dascandy

Reputation: 7302

+= → Add the right side to the left

=+ → Don't use this. Set the left to the right side.

Upvotes: 11

user744186
user744186

Reputation:

It's simple.

x += 1 is the same as x = x + 1 while

x =+ 1 will make x have the value of (positive) one

Upvotes: 3

James
James

Reputation: 9288

Because =+ is not a Java operator.

Upvotes: 0

Ilia Choly
Ilia Choly

Reputation: 18557

x += y 

is the same as

x = x + y

and

x =+ y

is wrong but could be interpreted as

x = 0 + y

Upvotes: 3

Keith Thompson
Keith Thompson

Reputation: 263627

Some historical perspective: Java inherited the += and similar operators from C. In very early versions of C (mid 1970s), the compound assignment operators had the "=" on the left, so

x =- 3;

was equivalent to

x = x - 3;

(except that x is only evaluated once).

This caused confusion, because

x=-1;

would decrement x rather than assigning the value -1 to it, so the syntax was changed (avoiding the horror of having to surround operators with blanks: x = -1;).

(I used -= and =- in the examples because early C didn't have the unary + operator.)

Fortunately, Java was invented long after C changed to the current syntax, so it never had this particular problem.

Upvotes: 0

Mario F
Mario F

Reputation: 47287

a += b equals a = a + b. a =+ b equals a = (+b).

Upvotes: 5

dlev
dlev

Reputation: 48606

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

Upvotes: 98

Jon Skeet
Jon Skeet

Reputation: 1503589

+= 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.

Upvotes: 24

Related Questions