C++ Operators
An operator is a symbol that works on one or two values. Some operators change a variable in place by using the value it already holds.
Adding and taking one
The ++ operator raises the value by 1. The -- operator then lowers the value by 1.
#include <iostream>
int main() {
int count = 5;
count++;
std::cout << count << std::endl;
count--;
std::cout << count << std::endl;
return 0;
}Updating in place
The += operator adds 6 to the total. The *= operator then multiplies the total by 3.
#include <iostream>
int main() {
int total = 4;
total += 6;
std::cout << total << std::endl;
total *= 3;
std::cout << total << std::endl;
return 0;
}The remainder
The % operator gives what a division leaves behind. Ten divided by three leaves a remainder of 1.
#include <iostream>
int main() {
std::cout << 10 % 3 << std::endl;
return 0;
}A score updated in steps
Each step works out a new score from the old one. The plain = sign stores each new value in score.
#include <iostream>
int main() {
int score = 10;
score = score + 5;
std::cout << score << std::endl;
score = score * 2;
std::cout << score << std::endl;
return 0;
}Example
#include <iostream>
int main() {
int score = 10;
score++;
std::cout << "Score: " << score << std::endl;
score += 9;
std::cout << "Score: " << score << std::endl;
score *= 2;
std::cout << "Score: " << score << std::endl;
score--;
std::cout << "Score: " << score << std::endl;
return 0;
}Key points
- The ++ operator adds 1 to a variable.
- The -- operator takes 1 away from a variable.
- The += operator adds a value and stores the result in the same variable.
- The *= operator multiplies a variable by a value and stores the result.
- The % operator gives the remainder after a division.
- A plain = sign stores a new value in a variable.
In this example, score starts at 10. The ++ operator raises it to 11, and += adds 9 to make 20. The *= operator doubles 20 to 40. The -- operator then lowers 40 to 39, and a line prints after each step.
Note
An update operator changes the variable itself, not a copy of it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A variable named x holds 5. What does x hold after the line x += 3; runs?