Difference between += and =+ in C++

前端 未结 4 1376
栀梦
栀梦 2020-12-11 16:15

While programming in C++, I often confuse both \"+=\" and \"=+\", the former being the operator I actually mean. Visual Studio seems to accept both, yet they behave differen

相关标签:
4条回答
  • 2020-12-11 16:28

    if you see = the first , it means you re-declare your variable value , but if you face + the first it means that you order the compiler to increment the value of the variable , keep it in you mind

    int x=20 ;
    x=+10 ;
    cout<< x <<endl ; // x  = 10
    
    
    x+=10 ;
    cout<< x<<endl ; // x= 10+10 = 20
    
    0 讨论(0)
  • 2020-12-11 16:36

    a =+ b means a = +b means a = b

    0 讨论(0)
  • 2020-12-11 16:42

    I may be remembering this wrong, but I think that in C, C++, and even Java (which has similar syntax to C and C++), =+ and += actually behave very similarly. The statement that =+ is assignment (equivalent to plain = operator), while += increases a variable's value by a certain amount, is INCORRECT.

    x += y as well as x =+ y will BOTH have the same effect (that is, both of these will cause the new value of x to be the old value of x + y). The difference comes in when you have a slightly more complex expression.

    z = (x += y) and z = (x =+ y) will have DIFFERENT outputs for the variable z. Let's look at each one of these:

    z = (x += y) will add y to x, and then set z to be the NEW value of x.

    z = (x =+ y) will set z to be the OLD value of x, and then add y to x.

    It's possible I got those 2 backwards, but I do remember reading somewhere before that the differences I describe here are the ACTUAL differences between those 2.

    0 讨论(0)
  • 2020-12-11 16:44

    =+ is really = + (assignment and the unary + operators).

    In order to help you remember +=, remember that it does addition first, then assignment. Of course that depends on the actual implementation, but it should be for the primitives.

    0 讨论(0)
提交回复
热议问题