Lesson 4 of 25

Operators

Arithmetic and Comparison

C++ supports standard arithmetic, comparison, and logical operators.

Example
// Arithmetic
int a = 10, b = 3;
cout << a + b << endl;  // 13
cout << a - b << endl;  // 7
cout << a * b << endl;  // 30
cout << a / b << endl;  // 3 (integer division)
cout << a % b << endl;  // 1 (modulus)

// Comparison
bool eq = (5 == 5);   // true
bool ne = (5 != 3);   // true
bool gt = (5 > 3);    // true
bool le = (3 <= 5);   // true

// Logical
bool and_r = true && false; // false
bool or_r = true || false;  // true
bool not_r = !true;         // false

// Increment/Decrement
int x = 5;
x++;  // 6
++x;  // 7
x--;  // 6

Bitwise Operators

C++ provides bitwise operators for low-level bit manipulation, useful in systems programming and competitive coding.

Example
int a = 5;  // binary: 0101
int b = 3;  // binary: 0011

cout << (a & b) << endl;  // AND: 1 (0001)
cout << (a | b) << endl;  // OR: 7  (0111)
cout << (a ^ b) << endl;  // XOR: 6 (0110)
cout << (~a) << endl;     // NOT: -6
cout << (a << 1) << endl; // Left shift: 10 (1010)
cout << (a >> 1) << endl; // Right shift: 2 (0010)

// Ternary operator
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";