简体   繁体   中英

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?

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) , ie 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

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

+= → Add the right side to the left

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

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

It's simple.

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

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

x += y 

is the same as

x = x + y

and

x =+ y

is wrong but could be interpreted as

x = 0 + y

因为=+不是 Java 运算符。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM