Often in programming, we need to update the status of a variable. For example, let’s say I’m coding a game where if the user presses a button, their score goes up by 5. The way I could write this in code would be:
score = score + 5;
There’s actually another way to do this which requires less typing! Enter augmented assignment operators. Don’t be afraid of their fancy name — these operators are simply an arithmetic operator and an assignment operator all in one.
In the example above, I could do the same thing with an augmented assignment operator like so:
score += 5;
There is an augmented assignment operator for all of the arithmetic operators. Here’s an example of all of them in action
int a = 1; a += 1; // equaivalent to a = a + 1; a -= 2; // equaivalent to a = a - 2; a *= 3; // equaivalent to a = a * 3; a /= 4; // equaivalent to a = a / 4; a %= 5; // equaivalent to a = a % 5;
What is the value of a?
0, the first 2 operators would turn the value to 0.