Operators (Arithmetic, Relational, Logical & Bitwise)
Operators are symbols that tell the compiler to perform specific mathematical, relational, logical, or bit-level manipulations on values (called operands).
1. Arithmetic Operators
Used for standard math:
• + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus — returns the remainder of integer division).
• Integer Division Warning: If both operands are integers, C++ truncates (chops off) the decimal part. For example, 7 / 2 evaluates to 3, not 3.5. To get 3.5, at least one number must be a decimal (7.0 / 2).
• Increment/Decrement: ++ adds 1 to a variable; -- subtracts 1.
2. Relational (Comparison) Operators
Compare two values and always return a bool (true or false):
• == (Equal to — do not confuse with single = which assigns a value!)
• != (Not equal to)
• > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or equal to).
3. Logical Operators
Combine or invert boolean conditions:
• && (Logical AND): Returns true only if both conditions are true.
• || (Logical OR): Returns true if at least one condition is true.
• ! (Logical NOT): Reverses a boolean (!true becomes false).
4. Bitwise Operators
Operate directly on the individual binary bits (0s and 1s) of integer types (used heavily in embedded systems, graphics, and networking):
• & (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT/flip bits), << (Left shift bits), >> (Right shift bits).
#include <iostream> int main() { int a = 10, b = 3; // Arithmetic std::cout << "Integer Division (10 / 3): " << (a / b) << "\n"; // Outputs 3 std::cout << "Remainder (10 % 3): " << (a % b) << "\n"; // Outputs 1 // Relational & Logical bool check = (a > 5) && (b != 0); // true AND true -> true (1) std::cout << "Logical Check: " << check << "\n"; // Bitwise (5 in binary is 0101, 3 is 0011) int bitwiseAnd = 5 & 3; // 0101 & 0011 = 0001 (1) std::cout << "Bitwise 5 & 3: " << bitwiseAnd << "\n"; return 0; }
Watch companion video on YouTube
Sign in to save your progress