< Previous | Contents | Next >

Using Combined Assignment Operators

There’s an even shorter version of the preceding line, which I use next.

score += 100;

This statement produces the same results as score = score þ 100;. The þ=

operator is called a combined assignment operator because it combines an

Performing Arithmetic Operations with Variables 27‌‌


arithmetic operation (addition, in this case) with assignment. This operator is shorthand for saying “add whatever’s on the right to what’s on the left and assign the result back to what’s on the left.”

There are versions of the combined assignment operator for all of the arithmetic operators you’ve met. To see a list, check out Table 1.2.


Table 1.2 Combined Assignment Operators

Operator

Example

Equivalent To

+=

x += 5;

x = x + 5;

-=

x -= 5;

x = x - 5;

*=

x *= 5;

x = x * 5;

/=

x /= 5;

x = x / 5;

%=

x %= 5;

x = x % 5;