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

CPP
#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:

(2) 2.2 The Modulus Operator %

% calculates the "remainder":

CPP
#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 ==!

CPP
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:

CPP
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:

TEXT 📖 Display only
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter a year: 
 is a leap year
 is not a leap year

Run result:

TEXT 📖 Display only
Please enter a year: 2024
2024 is a leap year

(2) 4.2 Short-circuit Evaluation

C++ has a "short-circuit" mechanism:

CPP
#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 =

CPP
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:

CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
a = 5, ++a = 6, a = 6
b = 5, b++ = 5, b = 6

💡 Memory trick:

(2) 6.2 Common Usage

CPP
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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:

TEXT 📖 Display only
Please enter your score (0-100): 85
Good! Grade: B

❓ FAQ

Q Why does 10 / 3 = 3 instead of 3.3333?
A Because both operands are integers, C++ performs integer division (discarding the decimal part). For a decimal result, make at least one operand a floating-point: 10.0 / 3 or 10 / 3.0 gives 3.33333.
Q Can % work with negative numbers?
A Yes, but the sign of the result depends on the dividend (C++11 standard). It's recommended to only use % with positive integers to avoid pitfalls. For example, (-10) % 3 gives -1.
Q Why can't I write 5 < x < 10?
A That's mathematical notation but C++ doesn't support it. The correct way is to connect two conditions with logical AND: if (5 < x && x < 10).
Q What's the real difference between i++ and ++i?
A 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


📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that lets the user enter two integers, then outputs their sum, difference, product, quotient, and remainder.
TEXT 📖 Display only
Please enter the first integer: 10
Please enter the second integer: 3
Sum: 13
Difference: 7
Product: 30
Quotient: 3
Remainor: 1
  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).
TEXT 📖 Display only
Please enter a three-digit number: 365
Hundreds: 3
Tens: 6
Ones: 5

(Hint: use the / and % operators)

  1. Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "guess the number" game:
  2. The program generates a random number from 1-100 (hint: use % 100 + 1 to map random numbers to 1-100)
  3. Let the user guess the number
  4. If the guess is too high, hint "Too high!"
  5. If the guess is too low, hint "Too low!"
  6. If the guess is correct, hint "Congratulations, you got it!"
  7. (Advanced: count how many attempts the user made)

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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏