Search code examples
c++operatorscompound-assignment

What is the meaning and name for "+=" in C++?


I am fairly new to C++ and I have been reading and writing some of my own code. I see these operators from time to time, if that is even the right word to use?

+= // Not sure what it means

So my question is: what do they mean/do, and what are they called?

For further reference, I'd like to know what they are called so I can easily look it up (searching simply for "+=" for instance yielded nothing).

Edit: For anyone else who does not know the meaning (or in my case knew the name of these) I found this Wikipedia link which might come of handy to other people: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B


Solution

  • Yes, these are operators. More specifically, they are known as compound assignment operators. Here's the full list of them:

    *= /= %= += -= >>= <<= &= ^= |=
    

    They are defined like so:

    The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

    So x += 5; is almost the same as x = x + 5;.

    You can think of it as a modifying addition. If you just do x + 5, the result of the expression is what you get if you add x and 5 together, but x hasn't changed. If you do x += 5;, x actually has 5 added to its value.