#110 – Combining the Arithmetic Operators with the Assignment Operator

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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: