# #110 – Combining the Arithmetic Operators with the Assignment Operator

October 5, 2010 Leave a comment

When you want to perform an arithmetic operation on a variable and assign the result back to the same variable, you can use the syntactical shortcut shown below.

Instead of writing :

x = x * 3; // Multiply x by 3

you can just write :

x *= 3; // Multiply x by 3

You can do the same thing with all arithmetic operators :

x += 10; // Add 10 to x x -= 10; // Subtract 10 from x x /= 10; // Divide x by 10 x %= 2; // Get remainder after dividing x by 2

These operators are known as compound assignment operators.