C++ Assignment Operators
In this page:
Basic Assignment Operator
The = operator takes whatever value results from the expression on its right and copies it into the variable on its left, overwriting anything previously stored there. This is the mechanism behind every piece of state your program keeps track of, from a running total to a user's chosen setting.
Example: Basic Assignment Operator
#include <iostream>
int main() {
int x;
x = 10; // copies 10 into x
std::cout << x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Addition Assignment Operator
+= folds addition and assignment into one step, so score += 10; reads as 'increase score by 10' and produces the exact same result as score = score + 10; with less typing. It's especially handy in loops, where a running total is updated on nearly every iteration.
Example: Addition Assignment Operator
#include <iostream>
int main() {
int score = 0;
score += 10;
std::cout << score << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Subtraction Assignment Operator
-= works the same way for subtraction, reducing a variable by the given amount in a single statement — useful for things like decrementing a countdown timer or reducing an inventory count after a purchase. Writing stock -= sold; is both shorter and more readable than the fully spelled-out version.
Example: Subtraction Assignment Operator
#include <iostream>
int main() {
int stock = 50;
int sold = 5;
stock -= sold;
std::cout << stock << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiplication and Division Assignment Operators
*= and /= apply the same shorthand pattern to multiplication and division, letting you scale a variable up or down in place, such as price *= 1.1; to apply a 10% increase. Because these operators use the variable's current value as part of the calculation, order matters if you're chaining several updates together.
Example: Multiplication and Division Assignment Operators
#include <iostream>
int main() {
double price = 100.0;
price *= 1.1; // apply a 10% increase
std::cout << price << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modulo Assignment Operator
%= divides a variable by a given number and replaces it with just the remainder, which is useful for wrapping a counter back to zero once it reaches a limit, like index %= arraySize; to keep an index cycling within valid bounds. This pattern shows up often in circular buffers and round-robin scheduling logic.
Example: Modulo Assignment Operator
#include <iostream>
int main() {
int index = 4;
int arraySize = 5;
index = (index + 1);
index %= arraySize; // wraps back within bounds
std::cout << index << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: