2️⃣

4.2 Augmented Assignment Operators

Chapter Table of Contents

Ch. 4 Operators

Section Table of Contents

 
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.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.