Assignment operators
- C++ course
- Beginner
- Lesson 25/116
- 4 min
Learn shortcut assignments with =, +=, -=, *=, /= and ++/--.
Assignment operators
The = operator assigns the right value to the left variable: x = 5;. This is the basic assignment operator.
C++ also offers compound assignment operators: +=, -=, *=, /=, %=. They perform an operation and an assignment in one step.
For example, x += 5 means the same as x = x + 5. Similarly x -= 3 = x = x - 3, x *= 2 = x = x * 2. These operators make code shorter and more readable.
Using compound assignment
Compound assignment operators are handy for updating a variable. To increment a counter each step, write count += 1; this is the same as count = count + 1.
Example: starting with score = 50. score += 20 → 70. score -= 10 → 60. The final score is 60.
These operators are not limited to numbers; += works with std::string for concatenation: text += "!". But multiplication and division apply only to numbers.
Practice Update with compound assignment
Inside main, declare int score = 50;. Update score with score += 20; and score -= 10;. Then print score with std::cout using std::endl. The output must be 60.
Starter code
#include <iostream>
int main() {
// Declare score and update it with +=, -=
// Print with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare score and update it with +=, -=
int score = 50;
score += 20;
score -= 10;
// Print with std::cout
std::cout << score << std::endl;
return 0;
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match assignment operators
| Term | Meaning |
|---|---|
= |
Basic assignment |
+= |
Add and assign |
-= |
Subtract and assign |
*= |
Multiply and assign |
2 What is x += 5 shorthand for?
- x = 5
- x = x + 5 Correct answer
- x + 5
- x == 5
Explanation: x += 5 is shorthand for x = x + 5.
3 Subtract and assign
score ____ 10;
score -= 10;
Explanation: The -= operator combines subtraction and assignment.