Notifications
Clear all
Topic starter 01/08/2025 11:22 pm
C++ operators are the building blocks of expressions—they let you perform calculations, compare values, assign data, and much more. Let’s break them down into categories so you can see how they work 🧠🔧
➕ Arithmetic Operators
Used for basic math operations:
int a = 10, b = 3;
std::cout << a + b; // Addition → 13
std::cout << a - b; // Subtraction → 7
std::cout << a * b; // Multiplication → 30
std::cout << a / b; // Division → 3
std::cout << a % b; // Modulus → 1
Also includes:
++a
ora++
→ Increment--a
ora--
→ Decrement
📝 Assignment Operators
Used to assign and update values:
int x = 5;
x += 3; // x becomes 8
x *= 2; // x becomes 16
Other examples: -=
, /=
, %=
, <<=
, >>=
, &=
, ^=
, |=
🔍 Comparison (Relational) Operators
Used to compare values:
int a = 5, b = 10;
std::cout << (a == b); // Equal → false
std::cout << (a != b); // Not equal → true
std::cout << (a < b); // Less than → true
std::cout << (a >= b); // Greater or equal → false
Also includes the spaceship operator <=>
in C++20 for three-way comparisons.
🔗 Logical Operators
Used to combine Boolean expressions:
bool sunny = true;
bool warm = false;
std::cout << (sunny && warm); // AND → false
std::cout << (sunny || warm); // OR → true
std::cout << (!sunny); // NOT → false
🧬 Bitwise Operators
Operate on binary representations:
int x = 5; // 0101
int y = 3; // 0011
std::cout << (x & y); // AND → 1
std::cout << (x | y); // OR → 7
std::cout << (x ^ y); // XOR → 6
std::cout << (~x); // NOT → -6
std::cout << (x << 1); // Left shift → 10
std::cout << (x >> 1); // Right shift → 2
❓ Ternary Operator
A shorthand for if-else
:
int age = 20;
std::string status = (age >= 18) ? "Adult" : "Minor";
📏 Other Operators
sizeof
→ Returns size in bytestypeid
→ Returns type info->
,.
→ Access members*
,&
→ Pointer dereference and address-of