Forum

Learn C++ Operators
 
Notifications
Clear all

Learn C++ Operators

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

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 or a++ → Increment
  • --a or a-- → 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 bytes
  • typeid → Returns type info
  • ->, . → Access members
  • *, & → Pointer dereference and address-of


   
Quote
Share: