SyntaxPilot
Courses/C++/Lesson 3
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 3 of 40

Operators

queued

These are the notes for C++ episode 3. Four friends split a ₹250 dosa bill, C++ says each pays ₹62, and ₹2 disappear. Following that story you will invent the operators yourself: why 250 / 4 gives 62 (integer division), why storing it in a double does not help, the % remainder operator, the shortcuts += and ++, the difference between x++ and ++x, comparison operators and the scary cout << 5 > 3 error, the logical operators &&, || and !, the 18 <= age <= 25 trap, and operator precedence (BODMAS for C++). Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler), and the output shown is the real output.

All snippets go inside this skeleton (the same one used in the video, so the line numbers in error messages match):

#include <iostream>
#include <string>
using namespace std;

int main() {
    // snippet goes here
    return 0;
}

The problem: ₹2 vanish from the dosa bill

Saturday night, four friends eat dosas and the bill is ₹250. Aman says, "Let's split it with C++."

int bill = 250;
int friends = 4;
cout << "Each pays: " << bill / friends << endl;
cout << "Collected: " << bill / friends * friends << endl;

Output:

Each pays: 62
Collected: 248

Everyone pays ₹62, that's ₹248, and the waiter says you are ₹2 short. No error, no warning, just missing money. The / (slash) is the division operator, and it just did something you did not expect.

What is an operator?

An operator is a symbol that tells C++ to do something with values: calculate, compare or combine. The values it works on are called operands. In bill / friends, / is the operator and bill and friends are the operands. An operator with two operands is binary (a + b); one with a single operand is unary (!student, x++).

Family Operators Gives you
Arithmetic + - * / % a number
Assignment = += -= *= /= %= stores a value
Increment / decrement ++ -- adds / subtracts 1
Comparison (relational) > < >= <= == != true / false
Logical && || ! true / false

Integer division: int ÷ int = int

250 is an int and 4 is an int. When both operands are integers, C++ does integer division: the answer is an int too. An int has no room for a decimal, so the .5 is chopped off (truncated), not rounded.

cout << 7 / 2 << " " << 9 / 10 << " " << -7 / 2 << endl;

Output: 3 0 -3

7 / 2 is 3, 9 / 10 is 0, and -7 / 2 is -3 (chopped toward zero, not rounded down to -4). This is a rule of C++, not a bug.

The obvious fix that does not work: a double box

In episode 2, double saved our decimals. So let's store the answer in a double:

int bill = 250, friends = 4;
double each = bill / friends;
cout << each << endl;

Output: 62

Still 62! The division happens first, in ints, and gives 62. Only then is 62 put into the double box. A bigger box, but the .5 fell out before it got there. The box doesn't matter; the division does.

The real fix: make one side a decimal

Think of a cashier with only notes and no coins: he can only hand back ₹62 each. Bring out the coins and it's ₹62.50. In C++, "bringing out the coins" means making one operand of the division a decimal, like 4.0 instead of 4:

int bill = 250;
cout << "Each pays: " << bill / 4.0 << endl;

Output: Each pays: 62.5

If either side is a double, C++ converts the other side to double too, and the whole division happens in decimals (7 / 2 prints 3, but 7.0 / 2 and 7 / 2.0 both print 3.5).

To turn a variable into a decimal (for example bill itself) you use a cast, static_cast<double>(bill). That comes properly in the next episode.

% (modulo): what is left over

Fine, pay in notes, but who covers the leftover ₹2? At home: 10 laddoos, 3 kids. Each gets 3 (10 / 3), and 1 is left in the box for mummy (10 % 3). The percent sign % is the modulo (remainder) operator: a % b is what is left after dividing a by b.

int bill = 250;
int friends = 4;
cout << "Each pays: " << bill / friends << endl;
cout << "Left over: " << bill % friends << endl;

Output:

Each pays: 62
Left over: 2

₹62 each, ₹2 left over. Aman pays the ₹2, because it was his idea.

Cricket overs from balls

27 balls have been bowled. How many overs? An over has 6 balls, so / 6 gives complete overs and % 6 gives the extra balls:

int balls = 27;
cout << "Overs: " << balls / 6 << "." << balls % 6 << endl;

Output: Overs: 4.3

4 overs and 3 balls. / tells you how many, % tells you how many are left. They always work as a pair.

Handy uses of %

int n = 17;
cout << n % 2 << endl;                    // 1
cout << 1234 % 10 << endl;                // 4
cout << 1234 / 10 << endl;                // 123
cout << -7 % 3 << " " << 7 % -3 << endl;  // -1 1
  • n % 2 == 0 means n is even; n % 2 != 0 means odd (17 is odd).
  • n % 10 gives the last digit; n / 10 removes it.
  • With negative numbers, the result takes the sign of the left operand (-7 % 3 is -1).
  • % works only on whole numbers. On a double:
double x = 7.5;
cout << x % 2 << endl;
main.cpp:7:15: error: invalid operands of types 'double' and 'int' to binary 'operator%'

+= and ++: the tired scorer's shortcut

You are the scorer in a gully cricket match. Every ball, you write the name runs twice:

int runs = 0;
runs = runs + 4;
runs = runs + 6;
runs = runs + 1;
cout << "Score: " << runs << endl;

Long lines invite typos (rums = runs + 4;). C++ has a shortcut:

int runs = 0;
runs += 4;
runs += 6;
runs++;
cout << "Score: " << runs << endl;

Output (the same for both versions): Score: 11

Same 11, half the typing. runs += 4 means runs = runs + 4 (a compound assignment), and runs++ adds 1 (an increment). Fun fact: the name C++ is exactly this, "C, plus one": one step beyond C.

Shortcut Means
x += 5 x = x + 5
x -= 5 x = x - 5
x *= 2 x = x * 2
x /= 2 x = x / 2 (still integer division for ints)
x %= 3 x = x % 3
x++ or ++x x = x + 1
x-- or --x x = x - 1

Starting from int x = 20;, printing after each step of x -= 5; x *= 2; x /= 4; x %= 3; x--; gives 15, 30, 7, 1, 0 (verified): 30 / 4 is 7 in integer division, and 7 % 3 is 1.

x++ vs ++x: the clinic token machine

At a clinic, the receptionist hands you token 5 and then turns the counter: that's token++ (post-increment: use the old value, then add 1). If she turns the counter first and then hands you the token, that's ++token (pre-increment: add 1, then use the new value).

int token = 5;
cout << token++ << endl;
cout << token << endl;
cout << ++token << endl;

Output:

5
6
7
  • token++ printed 5 (the old value); only afterwards did token become 6.
  • ++token made it 7 first, then printed 7.
  • On a line of its own (runs++; or ++runs;) both do exactly the same thing. The difference only matters when the value is also used in the same expression.
  • Never change the same variable twice in one expression (x = x++ + ++x;). This is undefined behaviour: the result is not reliable and can differ between compilers.

Comparison operators: yes-or-no questions

The restaurant offers free chai on bills over ₹200. The program must ask, "Is the bill more than 200?" The answer is yes or no: a bool.

Operator Meaning Example (bill = 250) Result
> greater than bill > 200 true
< less than bill < 200 false
>= greater than or equal bill >= 250 true
<= less than or equal bill <= 249 false
== equal to (two = signs) bill == 249 false
!= not equal to bill != 4 true

One = means put into the box (assignment). Two == mean ask: are these equal?

The cout << 5 > 3 error

cout << 5 > 3 << endl;
main.cpp:6:19: error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
    6 |     cout << 5 > 3 << endl;
      |                 ~~^~~~~~~

Why? The << arrows have higher precedence than >. So C++ groups it as (cout << 5) > (3 << endl). And 3 << endl (shift the number 3 by endl?) makes no sense, hence the error. Fix: put the comparison in brackets.

cout << (5 > 3) << endl;
cout << (250 == 249) << endl;

Output:

1
0

cout prints true as 1 and false as 0. Add cout << boolalpha; (from episode 2) to see the words true / false. Because a bool is really 1 or 0, you can even add them: (5 > 3) + (2 > 1) prints 2.

&& || !: two conditions at once

The college canteen gives a student discount, but only on bills over ₹200. Two conditions, and both must be true.

Operator Name True when Example
&& AND both sides are true student && bill > 200
|| OR at least one side is true student || bill > 300
! NOT flips true ↔ false !student
int bill = 250;
bool student = true;
cout << boolalpha;
cout << (student && bill > 200) << endl;
cout << (student && bill > 300) << endl;
cout << (student || bill > 300) << endl;
cout << !student << endl;

Output:

true
false
true
false
  1. Student AND bill over 200: both true, so true.
  2. Student AND bill over 300: the second fails, so false.
  3. Student OR bill over 300: one is enough, so true.
  4. NOT student: flips true to false.

Truth table

a b a && b a || b !a
true true true true false
true false false true false
false true false true true
false false false false true

Short-circuit evaluation

C++ stops as soon as the answer is known. In a && b, if a is false the whole thing is false, so b is never evaluated. In a || b, if a is true, b is skipped. This lets you guard a risky check:

int friends = 0;
int bill = 250;
cout << boolalpha;
cout << (friends != 0 && bill / friends > 50) << endl;

Output: false

friends != 0 is false, so bill / friends (a division by zero) never runs.

The 18 <= age <= 25 trap

A railway youth pass is for ages 18 to 25. In maths we write 18 ≤ age ≤ 25, so we type exactly that:

int age = 40;
cout << (18 <= age <= 25) << endl;

Output: 1

True, for a 40-year-old uncle! And g++ said nothing (with the default flags). C++ is not maths notation. <= is evaluated left to right (left-to-right associativity), two steps:

  1. 18 <= 40 is true, which is 1.
  2. 1 <= 25 is true.

The age never even reached the second check. Fix: two separate comparisons joined with &&:

int age = 40;
cout << (age >= 18 && age <= 25) << endl;

Output: 0

False: no pass for uncle. Always check a range with &&. Tip: compiling with -Wall makes g++ warn: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses].

Precedence: BODMAS for C++

Test marks: 8, 9 and 7 out of 10. The average:

int marks = 7;
cout << "Average: " << 8 + 9 + marks / 3 << endl;

Output: Average: 19

19 out of 10! Like BODMAS, / runs before +: first 7 / 3 = 2, then 8 + 9 + 2 = 19. Add brackets so the addition happens first:

int marks = 7;
cout << "Average: " << (8 + 9 + marks) / 3 << endl;

Output: Average: 8

(24 / 3 = 8.) When in doubt, add brackets. They cost nothing and make the code clearer.

Precedence table (highest first)

Level Operators What Associativity
1 ( ) brackets —
2 x++ x-- post-increment / decrement left to right
3 ++x --x ! -x unary: pre-increment, NOT, minus sign right to left
4 * / % multiply, divide, remainder left to right
5 + - add, subtract left to right
6 << >> cout / cin arrows (shift) left to right
7 < <= > >= comparison left to right
8 == != equality left to right
9 && AND left to right
10 || OR left to right
11 = += -= *= /= %= assignment (last) right to left

The << arrows sit below + but above >: that is why cout << 2 + 3 works but cout << 5 > 3 fails. Associativity decides the order when operators share a level. 2 + 3 * 4 prints 14 but (2 + 3) * 4 prints 20. 20 / 4 / 2 is (20 / 4) / 2 = 2 and 10 - 4 - 3 is (10 - 4) - 3 = 3 (left to right). x = y = 7; is x = (y = 7) (right to left), so both become 7. (All verified.)

Division by zero: a runtime crash

int bill = 250;
int friends = 0;
cout << "Each pays: " << bill / friends << endl;

It compiles without any error or warning (even with -Wall), then dies while running. With -O2 on our machine it printed Illegal instruction (exit code 132). The same code compiled with -O0 printed Floating point exception (exit code 136). Integer division by zero is undefined behaviour: the C++ standard says nothing about what happens, and in practice the program crashes. Notice that not even Each pays: was printed. With a double, 250.0 / 0.0 does not crash; it prints inf (infinity). Always check the divisor first (friends != 0 && ...), and a later episode adds if.

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
int ÷ int cout << bill / friends; no error; prints 62, not 62.5 bill / 4.0
Decimal box after the division double each = 250 / 4; no error; still 62 make an operand decimal: 250 / 4.0
Comparison in cout without brackets cout << 5 > 3 << endl; error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<' cout << (5 > 3) << endl;
% on a double double x = 7.5; cout << x % 2; error: invalid operands of types 'double' and 'int' to binary 'operator%' use int values
Maths-style range 18 <= age <= 25 no error; 1 even for age 40 age >= 18 && age <= 25
No brackets in an average 8 + 9 + marks / 3 no error; 19 (8 + 9 + marks) / 3
= instead of == cout << (price = 250); no error; stores 250 and prints 250 price == 250
Dividing by zero bill / friends with friends = 0 compiles; crashes at runtime (Illegal instruction at -O2, Floating point exception at -O0) check friends != 0 first

The silent ones (no error, wrong answer) are the most dangerous.

Mini project: bill splitter

Bill ₹250, four friends, a 10% tip, then the exact share, whole-rupee share, the leftover, and a budget check.

int bill = 250;
int friends = 4;
int tip = bill * 10 / 100;
int total = bill + tip;
cout << "Total with tip: " << total << endl;
cout << "Exact share: " << total / 4.0 << endl;
cout << "Each pays (whole): " << total / friends << endl;
cout << "Left for the tip jar: " << total % friends << endl;
bool fits = total / friends <= 70 && friends > 1;
cout << boolalpha << "Fits our budget: " << fits << endl;

Output:

Total with tip: 275
Exact share: 68.75
Each pays (whole): 68
Left for the tip jar: 3
Fits our budget: true
  • bill * 10 / 100: multiply first (2500), then divide (25). Written as bill * (10 / 100) it would be bill * 0 = 0, because 10 / 100 is integer division.
  • total / friends <= 70 && friends > 1: precedence does / first, then the comparisons, then &&, so no brackets are needed (but adding them is fine).
  • Try your own bill, number of friends and tip.

Practice

  1. Convert 135 minutes into hours and minutes with / and %.
  2. Print the last digit of 98765.
  3. Check whether the year 2026 is even.
  4. Write the youth-pass check for ages 18 to 25 and test it with 22 and 40.
  5. Predict a, b and c: int a = 10; int b = a++ + 5; int c = ++a + 5;
  6. Convert 3725 seconds into hours, minutes and seconds.
Solution

1. Output: 2 hours 15 minutes

int minutes = 135;
cout << minutes / 60 << " hours " << minutes % 60 << " minutes" << endl;

2. Output: Last digit: 5

int n = 98765;
cout << "Last digit: " << n % 10 << endl;

3. Output: Even: true

int year = 2026;
cout << boolalpha << "Even: " << (year % 2 == 0) << endl;

4. Output: Youth pass: true, then Youth pass: false

int age = 22;
cout << boolalpha;
cout << "Youth pass: " << (age >= 18 && age <= 25) << endl;
age = 40;
cout << "Youth pass: " << (age >= 18 && age <= 25) << endl;

5. Output: 12 15 17. b uses the old a (10), so b = 15, then a becomes 11. ++a makes a 12 first, so c = 17.

int a = 10;
int b = a++ + 5;
int c = ++a + 5;
cout << a << " " << b << " " << c << endl;

6. Output: 1h 2m 5s. seconds % 3600 is what is left after full hours; / 60 turns that into minutes.

int seconds = 3725;
cout << seconds / 3600 << "h " << seconds % 3600 / 60 << "m " << seconds % 60 << "s" << endl;

Quick quiz

What does this print?

cout << 7 / 2 * 2 << endl;
  • A. 7
  • B. 6
  • C. 7.0
  • D. 8
Answer

B: 6. 7 / 2 is integer division, so it gives 3 (the .5 is chopped). Then 3 * 2 = 6. / and * have the same precedence and run left to right. (Verified: the program prints 6.)

Interview questions

  • What is integer division? How do you get 62.5 from 250 and 4? With two integer operands the result is an integer, truncated toward zero: 250 / 4 is 62. Make one operand a double (250 / 4.0) or cast (static_cast<double>(bill) / friends).
  • Why does double each = 250 / 4; still give 62? The right side is computed first, entirely in int; only the finished 62 is converted to double.
  • x++ vs ++x? Both add 1. x++ gives the old value to the expression, ++x gives the new value. Alone on a line they are identical.
  • Can % be used with doubles? What is -7 % 3? No, % needs integers (use fmod from <cmath>). -7 % 3 is -1: the result has the sign of the left operand.
  • What is short-circuit evaluation? && / || evaluate the right side only if needed, so friends != 0 && bill / friends > 50 never divides by zero.
  • Why does cout << 5 > 3; fail? << has higher precedence than >, so it parses as (cout << 5) > (3 << endl). Write cout << (5 > 3);.
  • Precedence vs associativity? Precedence orders different operators (* before +); associativity orders operators of the same level (10 - 4 - 3 is 3, left to right; x = y = 7 goes right to left).
  • What happens on integer division by zero? Undefined behaviour: it compiles, then usually crashes at runtime (Floating point exception; our -O2 build showed Illegal instruction). Double division by zero gives inf.

Glossary

Term Plain meaning Example
Operator A symbol that tells C++ to calculate, compare or combine values +, /, >, &&
Operand A value an operator works on in bill / friends, bill and friends
Binary operator An operator with two operands a + b
Unary operator An operator with one operand !student, -x, x++
Expression Any piece of code that produces a value bill / 4.0, age >= 18
Arithmetic operator An operator that does maths + - * / %
Integer division Dividing two whole numbers; the decimal part is chopped off 250 / 4 is 62
Truncation Chopping off the decimal part (toward zero), not rounding 7 / 2 is 3, -7 / 2 is -3
Floating-point division Division where at least one side is a decimal, so the answer keeps decimals 250 / 4.0 is 62.5
Cast Converting a value to another type on purpose (next episode) static_cast<double>(bill)
Modulo (remainder) The % operator: what is left after dividing 250 % 4 is 2
Assignment Putting a value into a variable with = runs = 0;
Compound assignment A shortcut that does an operation and assigns in one step runs += 4 means runs = runs + 4
Increment Adding 1 to a variable with ++ runs++;
Decrement Subtracting 1 with -- wickets--;
Post-increment x++: use the old value, then add 1 cout << token++; prints 5, token becomes 6
Pre-increment ++x: add 1 first, then use the new value cout << ++token; prints 7
Comparison (relational) operator Compares two values and answers true or false bill > 200, price == 249
Equality operator == asks "equal?"; != asks "not equal?" table != 4
bool The type with only two values, true and false (printed as 1 and 0) bool student = true;
boolalpha Makes cout print true / false instead of 1 / 0 cout << boolalpha;
Logical operator Combines or flips true/false values &&, ||, !
AND (&&) True only when both sides are true student && bill > 200
OR (||) True when at least one side is true student || bill > 300
NOT (!) Flips true to false and false to true !student
Truth table A table listing the result for every true/false combination the AND / OR / NOT table above
Short-circuit evaluation && / || skip the right side when the left side already decides friends != 0 && bill / friends > 50
Precedence The rule for which operator runs first (BODMAS for C++) 8 + 9 + 7 / 3 does / first
Associativity The order for operators of the same precedence 20 / 4 / 2 = (20 / 4) / 2
Insertion operator << used with cout to send values to the screen cout << 62;
Undefined behaviour Code the C++ standard gives no meaning to; anything may happen, often a crash 250 / 0 with ints
Runtime error A failure that happens while the program runs, after it compiled fine Floating point exception
Compile error A mistake g++ finds before the program can run invalid operands ... 'operator%'
inf "Infinity": what a double divided by zero prints 250.0 / 0.0

Summary

  • int / int is integer division: the decimal is chopped. 250 / 4 = 62, and storing it in a double does not help.
  • Make one operand a decimal (250 / 4.0 = 62.5); a proper cast comes next episode.
  • % gives the remainder: leftovers, overs from balls, even/odd, last digit. Whole numbers only.
  • +=, -=, *=, /=, %= are compound assignments; ++ and -- add or subtract 1.
  • x++ uses then adds; ++x adds then uses. Alone on a line, they are the same.
  • > < >= <= == != give true/false. Comparing inside cout? Use brackets.
  • && needs both, || needs one, ! flips. They short-circuit.
  • 18 <= age <= 25 is a silent bug; write age >= 18 && age <= 25.
  • Precedence is BODMAS for C++. When in doubt, add brackets.
  • Integer division by zero is undefined behaviour and crashes at runtime.

Homework: 135 minutes into hours and minutes, the last digit of 98765, an even-number check, and the youth-pass check (all solved above, but try them yourself first).

Next episode: cin and type casting. So far the bill is written inside the code. Next time the user types the bill with cin, we read full names, and convert types properly with static_cast.