The difference between += and =+

前端 未结 8 1231
陌清茗
陌清茗 2020-12-01 05:28

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

相关标签:
8条回答
  • 2020-12-01 05:38

    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.

    0 讨论(0)
  • 2020-12-01 05:40

    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
    
    0 讨论(0)
  • Because =+ is not a Java operator.

    0 讨论(0)
  • 2020-12-01 05:51

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

    0 讨论(0)
  • 2020-12-01 06:01

    += → Add the right side to the left

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

    0 讨论(0)
  • 2020-12-01 06:03
    x += y 
    

    is the same as

    x = x + y
    

    and

    x =+ y
    

    is wrong but could be interpreted as

    x = 0 + y
    
    0 讨论(0)
提交回复
热议问题