1.6 Compound Assignment

Compound Assignments are shortcuts that do math operations quickly. For example, x += 1 adds 1 to the current value of x and assigns the result back to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+, just remember that the operation (+) is done first to produce the new value which is then assigned (=) back to the variable. So it’s operator then equal sign: +=.

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and --, also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1. Similarly, x-- serves as a shorthand for x = x - 1, allowing for efficient manipulation of numerical values in programming. These compound assignment operators enhance code readability and optimization, making it easier to express operations succinctly.

Operator

+

-

*

/

*

Written Out

x = x + 1

x = x + 1

x = x + 1

x = x + 1

x = x + 1

Compound

x += 1

x -= 1

x *= 2

x /= 2

x %= 2

Extra Consice

x++

++x

x--

--x