Explain it simply
Explain it simply
Operators are the small symbols that make a C++ program do something with values. The arithmetic operators + - * / and % calculate new numbers. The comparison operators == != < > <= >= ask a yes-or-no question and answer with a bool, true or false. The logical operators && || and ! combine several of those answers into one bigger condition.
The assignment operator = stores a value in a variable, and shortcuts such as += update a variable in place. Most operators behave the way they did in maths class. The surprises come from types: dividing one int by another int keeps only the whole-number part, and std::cout shows true as 1 unless you ask for words. Learn those few rules now and your totals and averages will come out right.
Problem → Why → Solution
The problem: an average that loses its decimals
A small grading program adds three test scores, 80, 82 and 83, and divides the total by 3. On paper the average is about 81.67, and the variable that stores it is even declared as double. Yet the program prints Average: 81. The compiler shows no error and no warning, so a bug like this can sit in a report card for weeks until someone checks the arithmetic by hand.
#include <iostream>
int main() {
int total = 80 + 82 + 83; // 245
int count = 3;
double average = total / count; // int / int runs first
std::cout << "Average: " << average << '\n'; // Average: 81
return 0;
}Why did the decimals disappear?
C++ chooses how to divide by looking at the two operands, not at the variable that receives the result. total and count are both int, so total / count is integer division: 245 / 3 is 81, and the remainder 2 is thrown away. Only after that is 81 converted to 81.0 and stored in average. Converting one operand first, as in static_cast<double>(total) / count, makes the division itself happen in floating point and gives 81.6667.
Core concept: operand types decide the result
An operator takes one or two operands and produces a new value, and the types of those operands decide which version of the operator runs. When both operands of / are integers, C++ performs integer division and truncates toward zero, so 7 / 2 is 3 and -7 / 2 is -3. When at least one operand is a floating-point type such as double, the other operand is converted first and 7.0 / 2 gives 3.5.
The % operator returns the remainder of integer division and works only on integer types. Its result takes the sign of the left operand, so -7 % 2 is -1, not 1.
Comparison operators (==, !=, <, >, <=, >=) always produce a bool. std::cout prints a bool as 1 or 0 by default; send std::boolalpha into the stream once and it prints true and false from then on. Logical operators combine bools: && is true only when both sides are true, || is true when at least one side is, and ! flips a value.
Both && and || short-circuit, meaning the right side is skipped when the left side already decides the answer. That is why count != 0 && total / count > 50 can never divide by zero.
Assignment (=) copies the right-hand value into the variable on the left. Compound operators (+=, -=, *=, /=, %=) read, compute and store in one step, so x += 5 means x = x + 5. ++x and x++ both add one: the prefix form gives you the new value and the postfix form gives you the old one.
When an expression mixes operators, precedence decides how it is grouped. * / and % bind tighter than + and -, arithmetic binds tighter than comparisons, and comparisons bind tighter than && and ||. Parentheses override all of these rules and make your intent obvious to the next reader.
| Group | Operators | Result |
|---|---|---|
| Arithmetic | + - * / % | a number of the operands' common type |
| Comparison | == != < > <= >= | bool |
| Logical | && || ! | bool |
| Assignment | = += -= *= /= %= | the updated variable |
- Check the operand types
- Group by precedence and parentheses
- Pick integer or floating-point math
- Get a number or a bool
The variable that receives the result never changes how the right-hand side is calculated.
General pattern
result = left + right; // also - * / %
bool answer = (left < right); // also == != > <= >=
bool both = conditionA && conditionB; // also || and !
variable += amount; // also -= *= /= %=
double exact = static_cast<double>(whole) / count;Arithmetic operators produce a number, comparison and logical operators produce a bool, and compound assignment updates a variable in place. When both operands are integers but you need a fraction, convert one of them with static_cast<double> before dividing.
Example: one pair of numbers, every kind of operator
The program below runs ten and three through arithmetic, comparison and compound assignment. Before you look at the output, predict each line yourself, paying special attention to the quotient and to how the bool is printed the first time.
#include <iostream>
int main() {
int x = 10;
int y = 3;
std::cout << "Sum: " << x + y << '\n';
std::cout << "Quotient: " << x / y << '\n';
std::cout << "Remainder: " << x % y << '\n';
std::cout << "Exact: " << static_cast<double>(x) / y << '\n';
std::cout << "Is x greater? " << (x > y) << '\n';
std::cout << std::boolalpha;
std::cout << "Is x greater? " << (x > y) << '\n';
std::cout << "Both positive? " << (x > 0 && y > 0) << '\n';
x += 5;
std::cout << "Updated x: " << x << '\n';
return 0;
}Code breakdown
- Integer division
std::cout << "Quotient: " << x / y << '\n';Both x and y are int, so 10 / 3 is integer division. The fractional part is dropped and the line prints 3, not 3.33.
- Remainder
x % y% gives what is left over after integer division: 3 goes into 10 three times with 1 left, so it prints 1. Together, x / y and x % y describe the whole division: 3 * 3 + 1 == 10.
- Forcing a fraction
static_cast<double>(x) / ystatic_cast<double>(x) turns 10 into 10.0 before dividing, so y is converted too and the division happens in floating point. std::cout shows six significant digits by default, which is why you see 3.33333.
- Printing a bool
std::cout << "Is x greater? " << (x > y) << '\n';x > y is true, but std::cout prints a bool as 1 until told otherwise. The parentheses are required: without them, << would bind first and the line would not compile.
- Words instead of digits
std::cout << std::boolalpha;std::boolalpha is a manipulator that stays switched on for the rest of the stream, so the next two bool values print as true. The && line is true because both comparisons are true.
- Compound assignment
x += 5;x += 5 reads x (10), adds 5 and stores 15 back into x, exactly like x = x + 5.
Sum: 13
Quotient: 3
Remainder: 1
Exact: 3.33333
Is x greater? 1
Is x greater? true
Both positive? true
Updated x: 15Precedence and short-circuit in practice
Precedence matters most when integer division sits inside a longer formula. Multiplying before dividing keeps the digits you need, while dividing first can wipe the value out. The second half of this snippet uses && as a guard: when there are no orders the left side is false, so the division on the right never runs.
#include <iostream>
int main() {
int price = 2500;
int percent = 15;
std::cout << "Discount A: " << price * percent / 100 << '\n'; // 375
std::cout << "Discount B: " << percent / 100 * price << '\n'; // 0
int orders = 0;
int revenue = 120000;
bool bigAverage = orders != 0 && revenue / orders > 50000;
std::cout << std::boolalpha << "Big average? " << bigAverage << '\n';
return 0;
}Discount A is 375 because 2500 * 15 is calculated first and only then divided by 100. Discount B is 0 because 15 / 100 is integer division and gives 0, and 0 times anything stays 0. Both lines use the same operators; only the order changed.
Increment and decrement: prefix and postfix
++ and -- add or subtract one. Written as a statement on its own line, ++count and count++ do exactly the same thing. The difference only shows up when the expression's value is used: the prefix form returns the variable after the change, while the postfix form returns a copy of the value from before it.
#include <iostream>
int main() {
int stock = 5;
int before = stock++; // before gets 5, then stock becomes 6
std::cout << "before = " << before << ", stock = " << stock << '\n';
int after = ++stock; // stock becomes 7, then after gets 7
std::cout << "after = " << after << ", stock = " << stock << '\n';
return 0;
}Change a variable once per expression
Writing something like i++ + i++ modifies the same variable twice with no ordering between the changes, which is undefined behaviour in C++: the compiler may produce any result. Keep ++ and -- on their own lines or in the update part of a for loop, where their meaning is never ambiguous.
In real projects
Where this shows up in real projects
Money is the classic place where integer arithmetic matters. Many shop and banking systems store prices as whole numbers of the smallest unit, such as kyat or cents, so that adding thousands of prices never collects floating-point rounding errors. Percentages are then computed with the multiply-first pattern, price * percent / 100, exactly as in the deeper section above.
The % operator shows up wherever things repeat in cycles. Pagination uses (items + perPage - 1) / perPage to count pages and index % perPage to find a position on a page. Clocks and timers turn raw seconds into minutes with / 60 and % 60, games use frame % 2 to alternate between two animations, and circular buffers wrap an index back to zero with index % capacity. Short-circuit && guards appear constantly in real code too, for example checking that a list is not empty before reading its first element.
Common mistakes
Common mistakes
1. Writing = where you meant ==
if (score = 100) does not compare anything: it stores 100 in score, and because 100 is non-zero the condition is always true. g++ -Wall reports warning: suggest parentheses around assignment used as truth value [-Wparentheses]. Use == to compare, and treat that warning as an error.
2. Printing a comparison without parentheses
std::cout << x > y; is parsed as (std::cout << x) > y, because << binds tighter than >. The result is a compile error: no match for 'operator>' (operand types are 'std::basic_ostream<char>' and 'int'). Write std::cout << (x > y); instead.
3. Testing for odd numbers with n % 2 == 1
For negative numbers the remainder is negative too: -7 % 2 is -1, so n % 2 == 1 claims that -7 is not odd. Test n % 2 != 0 instead, which works for every sign.
4. Assuming an int never runs out
On mainstream desktop and server compilers an int is 32 bits, which caps it at 2147483647. Adding two values of two billion overflows it, and signed overflow is undefined behaviour, not a predictable wrap-around. Use long long, which is at least 64 bits, for large counters and totals.
Best practices
Best practices
- Compile with -Wall -Wextra so the compiler flags slips such as = inside a condition.
- Multiply before you divide when you must stay in integers, and convert with static_cast<double> when you need a fraction.
- Add parentheses wherever a reader might hesitate about grouping, even when precedence already gives the right answer.
Mini challenge
Mini challenge: time, boxes and averages
Using only the operators from this lesson, turn raw numbers into useful facts for a small warehouse app.
- Split 7385 seconds into hours, minutes and seconds with / and %
- Work out how many boxes of 5 are needed for 17 items, rounding up, without using double
- Print the exact average of 245 points over 3 tests
- Print whether 7385 is odd as true or false, in a way that also works for negative numbers
#include <iostream>
int main() {
int totalSeconds = 7385;
int items = 17;
int boxSize = 5;
int points = 245;
int tests = 3;
// TODO: hours, minutes and seconds from totalSeconds using / and %
// TODO: boxes needed for items (round up, integers only)
// TODO: exact average of points over tests as a double
// TODO: print whether totalSeconds is odd as true/false
return 0;
}Expected: The output should be: 7385 s = 2 h 3 m 5 s Boxes needed: 4 Average: 81.6667 7385 is odd: true
Show hint
Hours are totalSeconds / 3600, and the seconds left over are totalSeconds % 3600, which you split again with / 60 and % 60. To round an integer division up, add boxSize - 1 before dividing: (items + boxSize - 1) / boxSize.
Show solution
#include <iostream>
int main() {
int totalSeconds = 7385;
int items = 17;
int boxSize = 5;
int points = 245;
int tests = 3;
int hours = totalSeconds / 3600;
int rest = totalSeconds % 3600;
int minutes = rest / 60;
int seconds = rest % 60;
std::cout << totalSeconds << " s = " << hours << " h " << minutes << " m "
<< seconds << " s\n";
int boxes = (items + boxSize - 1) / boxSize;
std::cout << "Boxes needed: " << boxes << '\n';
double average = static_cast<double>(points) / tests;
std::cout << "Average: " << average << '\n';
bool isOdd = totalSeconds % 2 != 0;
std::cout << std::boolalpha << totalSeconds << " is odd: " << isOdd << '\n';
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Operand types decide the arithmetic: int / int truncates toward zero, and % keeps the sign of the left operand.
- Convert one operand with static_cast<double> before dividing when you need a fraction.
- Comparisons and logical operators produce a bool, and std::boolalpha prints it as true or false.
- && and || skip their right side when the left side already decides the answer, which makes them useful guards.
- Use parentheses for clarity, == for comparison, and long long when an int could overflow.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation