Basic Operators
Overview
Operators are the mathematical engines that transform raw data. C++ supports standard arithmetic operators (+, -, *, /), the heavily utilized Modulo operator (%), and Assignment operators (=, +=, *=).
One of the most critical concepts for beginners to grasp in C++ is 'Integer Division'. Because C++ is strictly typed, if you divide two integers, the CPU physically cannot process decimals, so it mercilessly chops off (truncates) the decimal remainder.
Syntax
int a = 10, b = 3;
// --- 1. Arithmetic ---
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
// --- 2. Integer Division (TRUNCATES DECIMALS) ---
int div = a / b; // 3 (Not 3.333!)
// --- 3. Modulo (Gets the Remainder) ---
int rem = a % b; // 1 (Because 10 / 3 is 9, with 1 left over)
// --- 4. Increment/Decrement ---
a++; // a becomes 11 (Post-increment)
++a; // a becomes 12 (Pre-increment)Common Pitfalls
- Dividing variables to get a percentage, but using integers.
int accuracy = (hits / total) * 100;. If hits is 5 and total is 10,5 / 10evaluates to exactly0in integer math. Your accuracy will always be 0! You must cast one to a float first. - Confusing Post-Increment (
x++) with Pre-Increment (++x).int y = x++;assigns the OLD value to y, then increments x.int y = ++x;increments x first, then assigns the NEW value to y.
Interview Questions
++x (Pre-increment) often preferred over x++ (Post-increment) when writing complex C++ loops?When you use Post-increment (x++), the compiler is physically forced to create a temporary copy of the old variable in memory so it can return it before incrementing the original. For basic integers, this is negligible, but if 'x' is a massive Custom Iterator Object, copying it wastes significant CPU and RAM. Pre-increment avoids the copy entirely.
Real-World Example
Using the Modulo operator (%) to determine if a number is Even or Odd—a classic algorithm building block.
#include <iostream>
int main() {
int num = 42;
// Any number divided by 2 has a remainder of 0 if it is Even!
if (num % 2 == 0) {
std::cout << "The number is Even!\n";
} else {
std::cout << "The number is Odd!\n";
}
return 0;
}Check Your Knowledge
Test your understanding of Basic Operators with these quick questions.