C++: Operators Overview
Last updated: 2026-08-26
In Lesson 03 we learned how to store data using variables.
But just storing data isn't enough — we need to be able to perform operations on it, like arithmetic, comparisons, and logical judgments.
That's what operators are for. Just like +, -, ×, ÷ in math, C++ has its own set of operators.
1. Categories of Operators
C++ operators can be divided into several major categories:
| Category | Operators | Purpose |
|---|---|---|
| Arithmetic | +, -, *, /, % |
Mathematical operations |
| Relational | ==, !=, >, <, >=, <= |
Comparing values |
| Logical | &&, ` |
|
| Assignment | =, +=, -=, *=, /= |
Assigning values to variables |
| Increment/Decrement | ++, -- |
Add 1 or subtract 1 from a variable |
| Other | sizeof, ? :, ., -> |
Covered later |
2. Arithmetic Operators
(1) 2.1 Five Basic Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
Division | 10 / 3 |
3 (note!) |
% |
Modulus | 10 % 3 |
1 |
💡 Key point: The / operator trap
#include <iostream>
int main() {
int a = 10;
int b = 3;
std::cout << "10 / 3 = " << a / b << std::endl; // Outputs 3 (integer division, decimal part discarded)
double c = 10.0;
double d = 3.0;
std::cout << "10.0 / 3.0 = " << c / d << std::endl; // Outputs 3.33333
return 0;
}
Rules:
- When two integers are divided, the result is still an integer (decimal part is discarded)
- If either operand is a floating-point number, the result is a floating-point number
(2) 2.2 The Modulus Operator %
% calculates the "remainder":
#include <iostream>
int main() {
std::cout << "10 % 3 = " << 10 % 3 << std::endl; // 1
std::cout << "20 % 7 = " << 20 % 7 << std::endl; // 6
std::cout << "5 % 5 = " << 5 % 5 << std::endl; // 0
// Check even/odd
int num = 7;
if (num % 2 == 0) {
std::cout << num << " is Even" << std::endl;
} else {
std::cout << num << " is Odd" << std::endl;
}
return 0;
}
💡 Tip: % can only be used with integers, not floating-point numbers (10.5 % 3 will cause an error).
3. Relational Operators
Relational operators are used to compare two values, returning true or false.
(1) 3.1 Six Relational Operators
| Operator | Name | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 3 |
false |
!= |
Not equal to | 5 != 3 |
true |
> |
Greater than | 5 > 3 |
true |
< |
Less than | 5 < 3 |
false |
>= |
Greater than or equal to | 5 >= 5 |
true |
<= |
Less than or equal to | 5 <= 3 |
false |
💡 Key point: Don't write = instead of ==!
int age = 18;
if (age = 20) { // ❌ Error: this is assignment, not comparison!
std::cout << "An adult" << std::endl;
}
// The above code always outputs "An adult", because age = 20 assigns 20 to age,
// then checks if age is truthy (non-zero), which is always true
Correct way:
if (age == 20) { // ✅ Correct: this is comparison
std::cout << "Exactly 20 years old" << std::endl;
}
💡 Anti-bug technique: Put the constant on the left side — if you accidentally write = it will cause a compile error:
if (20 = age) { // ❌ Compile error: cannot assign to a constant
if (20 == age) { // ✅ Correct
4. Logical Operators
Logical operators are used to combine multiple conditions.
(1) 4.1 Three Logical Operators
| Operator | Name | Rule | Example |
|---|---|---|---|
&& |
Logical AND | Both sides must be true for the result to be true | (5 > 3) && (10 > 5) → true |
| ` | ` | Logical OR | |
! |
Logical NOT | Negates the value | !(5 > 3) → false |
▶ Example 1: Leap Year Checker (Difficulty ⭐)
#include <iostream>
int main() {
int year;
std::cout << "Please enter a year: ";
std::cin >> year;
// Leap year rule: divisible by 4 but not by 100, OR divisible by 400
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
std::cout << year << " is a leap year" << std::endl;
} else {
std::cout << year << " is not a leap year" << std::endl;
}
return 0;
}
Output:
Please enter a year:
is a leap year
is not a leap year
Run result:
Please enter a year: 2024
2024 is a leap year
(2) 4.2 Short-circuit Evaluation
C++ has a "short-circuit" mechanism:
&&: If the left side is false, the right side will not execute (because the result is already determined to be false)||: If the left side is true, the right side will not execute (because the result is already determined to be true)
#include <iostream>
int main() {
int x = 5;
// Short-circuit example
if (x > 10 && (x = 100)) { // x > 10 is false, so x = 100 won't execute
// ...
}
std::cout << "x = " << x << std::endl; // Outputs x = 5 (not changed to 100)
return 0;
}
💡 Tip: Using short-circuit evaluation, you can put "conditions more likely to be false" on the left side of && to improve program efficiency.
5. Assignment Operators
(1) 5.1 Basic Assignment Operator =
int x = 5; // Assign 5 to x
(2) 5.2 Compound Assignment Operators
| Operator | Equivalent to | Example |
|---|---|---|
+= |
x = x + y |
x += 5; → x = x + 5; |
-= |
x = x - y |
x -= 3; → x = x - 3; |
*= |
x = x * y |
x *= 2; → x = x * 2; |
/= |
x = x / y |
x /= 4; → x = x / 4; |
%= |
x = x % y |
x %= 3; → x = x % 3; |
Example:
#include <iostream>
int main() {
int x = 10;
x += 5; // x becomes 15
x -= 3; // x becomes 12
x *= 2; // x becomes 24
x /= 4; // x becomes 6
x %= 4; // x becomes 2
std::cout << "x = " << x << std::endl; // Outputs x = 2
return 0;
}
💡 Tip: Compound assignment operators are not only more concise to write, but in some cases the compiler can generate more efficient code.
6. Increment and Decrement Operators
++ and -- are C++'s signature operators (C++ got its name from them).
(1) 6.1 Basic Usage
| Operator | Name | Effect | Equivalent to |
|---|---|---|---|
++x |
Pre-increment | x is incremented first, then the new value is returned | x = x + 1; return x; |
x++ |
Post-increment | The original value is returned first, then x is incremented | temp = x; x = x + 1; return temp; |
--x |
Pre-decrement | x is decremented first, then the new value is returned | x = x - 1; return x; |
x-- |
Post-decrement | The original value is returned first, then x is decremented | temp = x; x = x - 1; return temp; |
▶ Example 2: Pre-increment vs Post-increment (Difficulty ⭐⭐)
#include <iostream>
int main() {
int a = 5;
int b = 5;
std::cout << "a = " << a << ", ++a = " << ++a << ", a = " << a << std::endl;
// Output: a = 5, ++a = 6, a = 6
std::cout << "b = " << b << ", b++ = " << b++ << ", b = " << b << std::endl;
// Output: b = 5, b++ = 5, b = 6
return 0;
}
Output:
a = 5, ++a = 6, a = 6
b = 5, b++ = 5, b = 6
💡 Memory trick:
++x: Increment first, then use (x is incremented first, then the new value is used)x++: Use first, then increment (the original value is used first, then x is incremented)
(2) 6.2 Common Usage
for (int i = 0; i < 10; i++) { // Here i++ and ++i have the same effect
// ...
}
int x = 5;
int y = x++; // y = 5, x = 6
int z = ++x; // x increments to 7 first, z = 7
💡 Recommendation: If there's no special need, prefer ++i over i++ — for custom types (covered later), ++i may be more efficient.
7. Operator Precedence
When an expression contains multiple operators, C++ determines the order of evaluation based on precedence.
(1) 7.1 Precedence Table (Partial)
| Precedence | Operators | Associativity |
|---|---|---|
| 1 (highest) | ++, -- (postfix), () (function call) |
Left to right |
| 2 | ++, -- (prefix), !, - (negation) |
Right to left |
| 3 | *, /, % |
Left to right |
| 4 | +, - (subtraction) |
Left to right |
| 5 | <, <=, >, >= |
Left to right |
| 6 | ==, != |
Left to right |
| 7 | && |
Left to right |
| 8 | ` | |
| 9 (lowest) | =, +=, -=, ... |
Right to left |
▶ Example 3: Impact of Precedence (Difficulty ⭐⭐)
#include <iostream>
int main() {
int result1 = 5 + 3 * 2; // First 3 * 2 = 6, then 5 + 6 = 11
int result2 = (5 + 3) * 2; // First 5 + 3 = 8 in parentheses, then 8 * 2 = 16
std::cout << "5 + 3 * 2 = " << result1 << std::endl; // 11
std::cout << "(5 + 3) * 2 = " << result2 << std::endl; // 16
return 0;
}
Output:
5 + 3 * 2 = 11
(5 + 3) * 2 = 16
💡 Golden rule: If you're unsure about precedence, use parentheses! Parentheses not only guarantee correctness but also make code more readable.
8. Practice: Grade Rating Program
▶ Example 4: Grade Rating Based on Score (Difficulty ⭐⭐)
#include <iostream>
int main() {
int score;
std::cout << "Please enter your score (0-100): ";
std::cin >> score;
if (score >= 90 && score <= 100) {
std::cout << "Excellent! Grade: A" << std::endl;
} else if (score >= 80 && score < 90) {
std::cout << "Good! Grade: B" << std::endl;
} else if (score >= 70 && score < 80) {
std::cout << "Medium! Grade: C" << std::endl;
} else if (score >= 60 && score < 70) {
std::cout << "Pass! Grade: D" << std::endl;
} else if (score >= 0 && score < 60) {
std::cout << "Not Pass! Grade: F" << std::endl;
} else {
std::cout << "Error: Score must be between 0-100!" << std::endl;
}
return 0;
}
Output:
Please enter your score (0-100):
Excellent! Grade: A
Good! Grade: B
Medium! Grade: C
Pass! Grade: D
Not Pass! Grade: F
Error: Score must be between 0-100!
Run result:
Please enter your score (0-100): 85
Good! Grade: B
❓ FAQ
10.0 / 3 or 10 / 3.0 gives 3.33333.% work with negative numbers?% with positive integers to avoid pitfalls. For example, (-10) % 3 gives -1.if (5 < x && x < 10).i++ (post-increment) returns the original value first then increments; ++i (pre-increment) increments first then returns the new value. For basic types like int there's no performance difference, but for iterators and other custom types ++i may be more efficient (no need to save the original value). Recommendation: prefer ++i when there's no special need.📖 Summary
- C++ has five major operator categories: arithmetic, relational, logical, assignment, and increment/decrement
- Integer division discards the decimal part; to get a decimal result, make at least one operand a floating-point number
- Don't write
=instead of==, or you'll get big bugs ++iincrements first then uses the value;i++uses the value first then increments- If you're unsure about operator precedence, use parentheses!
- Logical operators have short-circuit behavior, which can improve efficiency
📝 Exercises
- Basic (Difficulty ⭐): Write a program that lets the user enter two integers, then outputs their sum, difference, product, quotient, and remainder.
Please enter the first integer: 10
Please enter the second integer: 3
Sum: 13
Difference: 7
Product: 30
Quotient: 3
Remainor: 1
- Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter a three-digit number (e.g., 365), then outputs each digit separately (hundreds, tens, ones).
Please enter a three-digit number: 365
Hundreds: 3
Tens: 6
Ones: 5
(Hint: use the / and % operators)
- Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "guess the number" game:
- The program generates a random number from 1-100 (hint: use
% 100 + 1to map random numbers to 1-100) - Let the user guess the number
- If the guess is too high, hint "Too high!"
- If the guess is too low, hint "Too low!"
- If the guess is correct, hint "Congratulations, you got it!"
- (Advanced: count how many attempts the user made)
- C++ five major operator categories: arithmetic, relational, logical, assignment, increment/decrement
- Integer division discards the decimal part; convert operands to floating-point for decimal results
- Relational operators return bool values; note the difference between == and =
- Logical operators have short-circuit behavior
- When unsure about precedence, use parentheses
13. 🚀 Next Step
Now that you've learned operators, next we'll learn conditional statements (if-else) (Lesson 05) — enabling programs to make decisions and execute different code based on different conditions.