简体   繁体   中英

Difference between += and =+ in C++

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 differently and is a source for a lot of my bugs. I know that a += b is semantically equivalent to a = a+b, but what does "=+" do?

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

a =+ b表示a = +b表示a = b

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

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.

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