C++ Module 2 – Types, values and expressions
C++ operators, precedence and integer division
How C++ groups an expression by precedence and associativity, why -7 / 2 is -3 and -7 % 3 is -1, and which precedence traps the compilers flag.
What you will learn
- Evaluate expressions using precedence and associativity
- Use / and % correctly with negative numbers
- Predict which operands && and || evaluate
- Add parentheses where they make intent clear
Before you start
What you’ll learn · Before you start
What you will learn
- Evaluate expressions using precedence and associativity
- Use / and % correctly with negative numbers
- Predict which operands && and || evaluate
- Add parentheses where they make intent clear
Before you start
On this page
2 + 3 * 4 is 14, not 20, and -7 / 2 is -3, not -4. When an expression has several operators,
precedence: How tightly an operator holds its operands compared with other operators. * has a higher precedence than +, so a + b * c means a + (b * c). Precedence decides how an expression is grouped, not the order in which its operands are evaluated. decides which operands each one takes, and
associativity: The rule that groups a run of operators of equal precedence: from the left for most binary operators, so 20 - 6 - 4 is (20 - 6) - 4, and from the right for assignment and ?:, so x = y = 7 is x = (y = 7). decides how a run of operators of the same precedence is grouped. In
C++, *, / and % bind more tightly than + and -, comparisons more tightly than &&, and && more tightly
than ||, so a + b * c < d && e means ((a + (b * c)) < d) && e. Most operators group from the left,
10 - 4 - 3 is (10 - 4) - 3, while assignment groups from the right, so a = b = 0 sets both. Integer division
truncates towards zero, which gives -7 / 2 == -3, and % takes the sign of its left operand, so -7 % 3 == -1.
Precedence is also where many bugs hide: x & 1 == 0 does not test whether x is even. Every rule below is shown
with Apple clang 21 and GCC 16, including the warnings each compiler gives, and a later section uses all of them in a
leap-year and weekday calculation checked against 146,097 days of the calendar.
Precedence picks the operands; associativity breaks ties
The program below prints eight expressions with a = 2, b = 3 and c = 4. Read each value against the grouping
written beside it:
#include <print>
int main() {
int a = 2, b = 3, c = 4;
std::println("a + b * c = {:>3} same as a + (b * c)", a + b * c);
std::println("(a + b) * c = {:>3}", (a + b) * c);
std::println("20 - 6 - 4 = {:>3} same as (20 - 6) - 4", 20 - 6 - 4);
std::println("120 / 6 / 2 = {:>3} same as (120 / 6) / 2", 120 / 6 / 2);
std::println("a < b == b < c = {} same as (a < b) == (b < c)", a < b == b < c);
std::println("a > b || b < c && c > 9 = {} same as (a > b) || ((b < c) && (c > 9))", a > b || b < c && c > 9);
int x, y;
x = y = 7; // assignment groups from the right: x = (y = 7)
x += y *= 2; // y becomes 14, then x becomes 7 + 14
std::println("x = {}, y = {}", x, y);
std::println("c > 3 ? 1 : 0 + 10 = {} the ?: comes last: c > 3 ? 1 : (0 + 10)", c > 3 ? 1 : 0 + 10);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra grouping.cpp -o grouping
./grouping
g++-16 -std=c++23 -Wall -Wextra grouping.cpp -o grouping
./grouping
""") Output
$ clang++ -std=c++23 -Wall -Wextra grouping.cpp -o grouping
grouping.cpp:10:107: warning: '&&' within '||' [-Wlogical-op-parentheses]
10 | std::println("a > b || b < c && c > 9 = {} same as (a > b) || ((b < c) && (c > 9))", a > b || b < c && c > 9);
| ~~ ~~~~~~^~~~~~~~
grouping.cpp:10:107: note: place parentheses around the '&&' expression to silence this warning
10 | std::println("a > b || b < c && c > 9 = {} same as (a > b) || ((b < c) && (c > 9))", a > b || b < c && c > 9);
| ^
| ( )
1 warning generated.
$ ./grouping
a + b * c = 14 same as a + (b * c)
(a + b) * c = 20
20 - 6 - 4 = 10 same as (20 - 6) - 4
120 / 6 / 2 = 10 same as (120 / 6) / 2
a < b == b < c = true same as (a < b) == (b < c)
a > b || b < c && c > 9 = false same as (a > b) || ((b < c) && (c > 9))
x = 21, y = 14
c > 3 ? 1 : 0 + 10 = 1 the ?: comes last: c > 3 ? 1 : (0 + 10)
$ g++-16 -std=c++23 -Wall -Wextra grouping.cpp -o grouping
grouping.cpp: In function 'int main()':
grouping.cpp:9:72: warning: suggest parentheses around comparison in operand of '==' [-Wparentheses]
9 | std::println("a < b == b < c = {} same as (a < b) == (b < c)", a < b == b < c);
| ~~^~~
grouping.cpp:10:107: warning: suggest parentheses around '&&' within '||' [-Wparentheses]
10 | std::println("a > b || b < c && c > 9 = {} same as (a > b) || ((b < c) && (c > 9))", a > b || b < c && c > 9);
| ~~~~~~^~~~~~~~
$ ./grouping
a + b * c = 14 same as a + (b * c)
(a + b) * c = 20
20 - 6 - 4 = 10 same as (20 - 6) - 4
120 / 6 / 2 = 10 same as (120 / 6) / 2
a < b == b < c = true same as (a < b) == (b < c)
a > b || b < c && c > 9 = false same as (a > b) || ((b < c) && (c > 9))
x = 21, y = 14
c > 3 ? 1 : 0 + 10 = 1 the ?: comes last: c > 3 ? 1 : (0 + 10)
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 grouping_session.py
The $ lines are commands, and what each one printed follows it until the next $. Every line prints the value of
an expression next to the same expression with all its parentheses written out. The minus and the division group from
the left: grouping from the right would give 20 - (6 - 4) = 18 and 120 / (6 / 2) = 40. Assignment groups from the
right, so x = y = 7 stores 7 in y and then the result in x, and x += y *= 2 doubles y before adding it to
x. The conditional operator ?: sits almost at the bottom of the table, below +, so in c > 3 ? 1 : 0 + 10 the
addition belongs to the third operand.
Step through four of those lines and watch one operator at a time take its operands, the tightest first:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- * before +. In
a + b * cthe*has the higher precedence, so it takesbandc: 3 × 4 = 12, then 2 + 12 = 14. The program printed 14, and 20 for(a + b) * c. - Equal ranks, from the left.
20 - 6 - 4holds two operators of the same rank. Minus groups from the left, so the first one runs first: (20 − 6) − 4 = 10. Grouped from the right it would be 20 − 2 = 18. - Assignment, from the right.
x = y = 7groups from the right:y = 7comes first, and its result, 7, is stored inx. The next line,x += y *= 2, doublesyto 14 and adds it tox, so the program printed x = 21, y = 14. - Comparisons bind first. Five operators now. The three comparisons rank above
&&and||, so each takes the names beside it: with a = 2, b = 3 and c = 4,a > bis false,b < ctrue andc > 9false. - && before ||.
&&ranks above||, so it takes the two comparisons beside it: true && false is false.||gets what is left, false || false, and the program printed false. - Grouping is not timing. Precedence says which operands belong to which operator, not when each one is evaluated.
||still evaluates its left operand first, as the section on && and || shows.
The last grouping in the figure is one the compilers warn about. Both compilers accept the program, yet GCC asks for
parentheses around a < b == b < c, and both ask for them around the && inside an ||. The grouping there is
exactly what the program prints, but it is a grouping that readers often get wrong, which is why rule ES.41 of the
C++ Core Guidelines says to parenthesise when in doubt.
The C++ standard defines precedence through its grammar rather than a table, but the result can be summarised. From the operators that bind most tightly to those that bind least:
| Rank | Operators | Grouping |
|---|---|---|
| 1 | scope a::b |
left |
| 2 | postfix a++ a--, call f(x), subscript a[i], member a.b p->b |
left |
| 3 | prefix ++a --a, unary +a -a !a ~a, *p, &a, sizeof, casts |
right |
| 4 | multiplicative * / % |
left |
| 5 | additive + - |
left |
| 6 | shifts << >> |
left |
| 7 | three-way comparison <=> |
left |
| 8 | relational < <= > >= |
left |
| 9 | equality == != |
left |
| 10 | bitwise AND & |
left |
| 11 | bitwise XOR ^ |
left |
| 12 | bitwise OR | |
left |
| 13 | logical AND && |
left |
| 14 | logical OR || |
left |
| 15 | conditional ?:, assignment = += and the other compound assignments, throw |
right |
| 16 | comma , |
left |
Two rows deserve a second look. The shifts sit below +, so 1 << n + 1 shifts by n + 1; and the bitwise
operators sit below the comparisons, which is the trap of a later section. When << writes to std::cout, the same
row applies: std::cout << a + b prints the sum, but std::cout << a & b tries to apply & to the stream and does
not compile.
Key idea
Precedence and associativity decide only how an expression is grouped, and the grouping is the same in every compiler. Where a reader could group it another way, write the parentheses the warnings ask for.
Checkpoint
Check: Precedence and associativity
Integer division truncates, so the remainder can be negative
For integers, / discards the fraction, truncating towards zero, and % gives the remainder that goes with it,
so that (a / b) * b + a % b == a always holds. Since C++11 the standard fixes both, and the consequence is that
the remainder has the sign of the left operand:
#include <print>
#include <utility>
// Rounds the quotient down instead of towards zero (b must not be 0).
int floor_div(int a, int b) {
int q = a / b;
if (a % b != 0 && (a < 0) != (b < 0)) --q;
return q;
}
// A remainder from 0 to b - 1 for a positive b, as calendars and clocks want.
int wrap_mod(int a, int b) {
int r = a % b;
return r < 0 ? r + b : r;
}
int main() {
std::println(" a b | a / b a % b | floor_div | (a / b) * b + a % b == a");
for (auto [a, b] : {std::pair{7, 2}, {-7, 2}, {7, -2}, {-7, -2}, {-7, 3}}) {
std::println("{:>3} {:>3} | {:>5} {:>5} | {:>9} | {}", a, b, a / b, a % b, floor_div(a, b), (a / b) * b + a % b == a);
}
std::println("-7 % 3 = {}, but wrap_mod(-7, 3) = {}", -7 % 3, wrap_mod(-7, 3));
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra division.cpp -o division
./division
g++-16 -std=c++23 -Wall -Wextra division.cpp -o division
./division
""") Output
$ clang++ -std=c++23 -Wall -Wextra division.cpp -o division $ ./division a b | a / b a % b | floor_div | (a / b) * b + a % b == a 7 2 | 3 1 | 3 | true -7 2 | -3 -1 | -4 | true 7 -2 | -3 1 | -4 | true -7 -2 | 3 -1 | 3 | true -7 3 | -2 -1 | -3 | true -7 % 3 = -1, but wrap_mod(-7, 3) = 2 $ g++-16 -std=c++23 -Wall -Wextra division.cpp -o division $ ./division a b | a / b a % b | floor_div | (a / b) * b + a % b == a 7 2 | 3 1 | 3 | true -7 2 | -3 -1 | -4 | true 7 -2 | -3 1 | -4 | true -7 -2 | 3 -1 | 3 | true -7 3 | -2 -1 | -3 | true -7 % 3 = -1, but wrap_mod(-7, 3) = 2
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 division_session.py
-7 / 2 is -3 rather than -4, and -7 % 2 is -1. Mathematics usually prefers the quotient rounded down and a remainder
between 0 and b - 1; for positive operands the two agree, and for negative ones you write it yourself, as
floor_div and wrap_mod do. wrap_mod(-7, 3) gives 2, the answer calendars and clocks need. Step through the row
for -7 and 2, then the program’s last line, and see where each of those numbers comes from:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- The exact quotient. -7 divided by 2 is exactly -3.5. An int cannot hold the .5, so the division has to drop it one way or the other.
- Towards zero. C++ drops the fraction towards zero, so
-7 / 2is -3, as both builds printed.floor_divrounds down instead and returns -4. - The remainder that fits.
%gives the remainder that makes(a / b) * b + a % bequala: (-3) × 2 + r = -7, so r is -1. Its sign is the sign of -7, the left operand. - The rounded-down pair. With the quotient -4, the remainder that fits is +1: (-4) × 2 + 1 = -7. Both pairs are sound arithmetic; C++ fixes the first one, and floor_div gives the quotient of the second.
- Back into range.
-7 % 3is -1, which is no position on a clock of 3.wrap_modadds 3 to a negative remainder and returns 2, the value the program printed.
Testing for an odd number with n % 2 == 1
For a negative odd n, n % 2 is -1, as the row for -7 and 2 shows, so n % 2 == 1 calls -7 even. Write
n % 2 != 0, which is right for every sign.
Two more rules complete the picture: dividing by zero is
undefined behaviour: What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level. More in “Object lifetime and undefined behaviour in C++”, and so is INT_MIN / -1, whose true result,
2,147,483,648, does not fit in an int.
Key idea
/ truncates towards zero and % keeps (a / b) * b + a % b == a true, so a negative left operand gives a negative
remainder. Add b back, as wrap_mod does, when you need a value from 0 to b − 1.
Checkpoint
Check: Truncating division and its remainder
Short-circuit evaluation skips what cannot change the result
&& and || evaluate their left operand first and evaluate the right one only when it can still change the result.
This is called short-circuit evaluation: Evaluating the right operand of && or || only when the left one leaves the result open: in false && f() and in true || f(), f is never called. It lets a check guard the operand after it, as in i < v.size() && v[i] > 0.:
#include <print>
#include <vector>
bool check(const char* name, bool result) {
std::println(" evaluating {}", name);
return result;
}
int main() {
std::println("false && B:");
bool r1 = check("A", false) && check("B", true);
std::println("true || B:");
bool r2 = check("A", true) || check("B", true);
std::println("false & B, with the bitwise &:");
bool r3 = check("A", false) & check("B", true);
std::println("results: {} {} {}", r1, r2, r3);
// Short-circuiting makes the index check protect the element access.
std::vector<int> v{4, 8};
std::size_t i = 5;
if (i < v.size() && v[i] > 0) std::println("positive");
else std::println("index {} is outside the vector, and v[{}] was never read", i, i);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra short_circuit.cpp -o short_circuit
./short_circuit
g++-16 -std=c++23 -Wall -Wextra short_circuit.cpp -o short_circuit
./short_circuit
""") Output
$ clang++ -std=c++23 -Wall -Wextra short_circuit.cpp -o short_circuit
short_circuit.cpp:15:15: warning: use of bitwise '&' with boolean operands [-Wbitwise-instead-of-logical]
15 | bool r3 = check("A", false) & check("B", true);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| &&
short_circuit.cpp:15:15: note: cast one or both operands to int to silence this warning
1 warning generated.
$ ./short_circuit
false && B:
evaluating A
true || B:
evaluating A
false & B, with the bitwise &:
evaluating A
evaluating B
results: false true false
index 5 is outside the vector, and v[5] was never read
$ g++-16 -std=c++23 -Wall -Wextra short_circuit.cpp -o short_circuit
$ ./short_circuit
false && B:
evaluating A
true || B:
evaluating A
false & B, with the bitwise &:
evaluating A
evaluating B
results: false true false
index 5 is outside the vector, and v[5] was never read
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 short_circuit_session.py
After false && and after true ||, the second check never runs: its output line is missing. The bitwise & has no
such rule, so both checks run, and Apple clang warns that a & between two bool values was probably meant to be
&&. Short-circuiting is what makes the last test safe: i < v.size() && v[i] > 0 reads v[i] only after the index
has passed the check, so element 5 of a two-element vector is never touched. Swap the two operands and the program
reads outside the vector before it tests anything. Step through that last test the way the program ran it:
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- The left operand first.
&&always evaluates its left operand first.iis 5 andvholds 2 values, soi < v.size()is false. - && stops. false && anything is false, so
&&returns false without evaluating its right operand.v[i] > 0never runs, and v[5], past the end of the vector, is never read. - Both builds agree. The else branch printed "index 5 is outside the vector, and v[5] was never read", with Apple clang and with GCC.
- Swapped, it reads first. Written as
v[i] > 0 && i < v.size(), the read of v[5] would run first, before any check, and reading past the end is undefined behaviour. The guard has to be the left operand.
The false left operand settled the result, so neither build evaluated the right one. The rule fixes an order as well:
the left operand of && or || is evaluated completely, side effects included, before the right one starts, a
guarantee the next lesson builds on.
Key idea
Put the check that makes an operand safe on the left of &&: the right operand runs only after the left one has
come out true.
Checkpoint
Check: Short-circuit evaluation
Two groupings that mislead: a bitwise test and a chained comparison
The two expressions of this section look right and mean something else. The first tests whether x is even; its
two trees show how the compiler groups it, and how its writer meant it:
How x & 1 == 0 is grouped
Text description of the diagram
Two expression trees side by side. In each, an operator is a circle whose branches lead to its operands.
- Left, the expression as written, x & 1 == 0. Because == has higher precedence than &, the top node is &, with x on one branch and the comparison 1 == 0 on the other. 1 == 0 is false, which converts to 0, so the result is x & 0: always false.
- Right, the expression as meant, (x & 1) == 0. The top node is ==, comparing x & 1 with 0. x & 1 is the lowest bit of x, so the result is true for every even x.
The comparisons bind more tightly than the bitwise operators &, ^ and |, an ordering inherited from C. So
x & 1 == 0 compares 1 with 0 first, which gives false, converted to 0, and then computes x & 0, which is 0 for
every x. A chain of comparisons misleads in a different way: low < mid < high is (low < mid) < high, which
compares a bool, integral promotion: The conversion of an operand narrower than int, such as bool, char, unsigned char or short, to int before arithmetic, so that 200 + 100 with unsigned char operands is the int 300. More in “Integer overflow and signed/unsigned conversions” to 0 or 1, with high.
parity.cpp
#include <print>
int main() {
for (int x : {6, 7}) {
bool even_wrong = x & 1 == 0; // parsed as x & (1 == 0), which is x & 0
bool even_right = (x & 1) == 0;
std::println("x = {}: x & 1 == 0 gives {}, (x & 1) == 0 gives {}", x, even_wrong, even_right);
}
} chained.cpp
#include <print>
int main() {
int low = 1, mid = 5, high = 3;
bool in_order = low < mid < high; // parsed as (low < mid) < high, which is true < 3
std::println("low < mid < high gives {}", in_order);
std::println("low < mid && mid < high gives {}", low < mid && mid < high);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra parity.cpp -o parity
./parity
g++-16 -std=c++23 -Wall -Wextra parity.cpp -o parity
./parity
clang++ -std=c++23 -Wall -Wextra chained.cpp -o chained
g++-16 -std=c++23 -Wall -Wextra chained.cpp -o chained
./chained
""") Output
$ clang++ -std=c++23 -Wall -Wextra parity.cpp -o parity
parity.cpp:5:29: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
5 | bool even_wrong = x & 1 == 0; // parsed as x & (1 == 0), which is x & 0
| ^~~~~~~~
parity.cpp:5:29: note: place parentheses around the '==' expression to silence this warning
5 | bool even_wrong = x & 1 == 0; // parsed as x & (1 == 0), which is x & 0
| ^
| ( )
parity.cpp:5:29: note: place parentheses around the & expression to evaluate it first
5 | bool even_wrong = x & 1 == 0; // parsed as x & (1 == 0), which is x & 0
| ^
| ( )
1 warning generated.
$ ./parity
x = 6: x & 1 == 0 gives false, (x & 1) == 0 gives true
x = 7: x & 1 == 0 gives false, (x & 1) == 0 gives false
$ g++-16 -std=c++23 -Wall -Wextra parity.cpp -o parity
parity.cpp: In function 'int main()':
parity.cpp:5:33: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
5 | bool even_wrong = x & 1 == 0; // parsed as x & (1 == 0), which is x & 0
| ~~^~~~
$ ./parity
x = 6: x & 1 == 0 gives false, (x & 1) == 0 gives true
x = 7: x & 1 == 0 gives false, (x & 1) == 0 gives false
$ clang++ -std=c++23 -Wall -Wextra chained.cpp -o chained
chained.cpp:5:31: error: chained comparison 'X < Y < Z' does not behave the same as a mathematical expression [-Wparentheses]
5 | bool in_order = low < mid < high; // parsed as (low < mid) < high, which is true < 3
| ^
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra chained.cpp -o chained
chained.cpp: In function 'int main()':
chained.cpp:5:25: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
5 | bool in_order = low < mid < high; // parsed as (low < mid) < high, which is true < 3
| ~~~~^~~~~
$ ./chained
low < mid < high gives true
low < mid && mid < high gives false
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 traps_session.py
Both compilers warn about x & 1 == 0 under -Wparentheses, which -Wall enables, and the program prints false
for 6 and for 7 alike. With the parentheses, (x & 1) == 0 is true for 6. The chained comparison shows a difference
between the compilers. GCC warns and builds it, and the program says that 1 < 5 < 3 is true. Apple clang refuses to
build it at all: since Clang 21, a chained comparison is an error by default, as its release notes state, and
-Wno-error=parentheses would turn it back into a warning. The fix in both cases is the expression you meant:
(x & 1) == 0, and low < mid && mid < high.
Key idea
Where &, ^ or | meets a comparison, or one comparison follows another, the compiler’s grouping is not the one a
reader expects: write the parentheses, or the &&, that say what you mean.
Checkpoint
Check: Groupings that mislead
A weekday formula fails exactly where the remainder goes negative
A Gregorian year is a leap year when it is divisible by 4, except century years, which are leap years only when
divisible by 400. In C++ that is (year % 4 == 0 && year % 100 != 0) || year % 400 == 0. The parentheses are not
needed, because && binds more tightly than ||, but they show the reader the rule’s structure, and both compilers
ask for them.
The day of the week can be computed with Zeller’s congruence, a formula from a short paper by Christian Zeller.
It counts January and February as months 13 and 14 of the previous year, splits the year into the century j and
the year within the century k, and takes the sum of a few terms modulo 7. The formula is often printed with a
- 2j term, which is the same as + 5j modulo 7 in mathematics but not in C++: when the sum is negative, %
returns a negative number unless 7 divides the sum, and an index into a list of day names cannot be negative. This
program tries both against the calendar of <chrono>, for every day of a 400-year cycle:
#include <chrono>
#include <print>
bool is_leap_year(int year) {
// && binds tighter than ||; the parentheses say so for the reader (and silence -Wparentheses).
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
// Zeller's congruence for the Gregorian calendar: 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
// January and February count as months 13 and 14 of the previous year.
int zeller(int year, int month, int day) {
if (month < 3) {
month += 12;
year -= 1;
}
int k = year % 100;
int j = year / 100;
return (day + 13 * (month + 1) / 5 + k + k / 4 + j / 4 + 5 * j) % 7;
}
// The same formula as it is often printed, with - 2j instead of + 5j (equal modulo 7).
int zeller_minus(int year, int month, int day) {
if (month < 3) {
month += 12;
year -= 1;
}
int k = year % 100;
int j = year / 100;
return (day + 13 * (month + 1) / 5 + k + k / 4 + j / 4 - 2 * j) % 7;
}
int main() {
constexpr const char* names[] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
using namespace std::chrono;
int checked = 0, plus_ok = 0, minus_ok = 0, negative = 0, leap_ok = 0;
// Every day of a 400-year cycle, checked against <chrono>.
for (sys_days d = sys_days{2000y / January / 1}; d < sys_days{2400y / January / 1}; d += days{1}) {
year_month_day ymd{d};
int y = int(ymd.year()), m = int(unsigned(ymd.month())), dd = int(unsigned(ymd.day()));
int expected = (weekday{d}.c_encoding() + 1) % 7; // c_encoding: 0 = Sunday
++checked;
plus_ok += zeller(y, m, dd) == expected;
minus_ok += zeller_minus(y, m, dd) == expected;
negative += zeller_minus(y, m, dd) < 0;
}
for (int y = 1600; y < 2400; ++y) leap_ok += is_leap_year(y) == year{y}.is_leap();
std::println("days checked: {}", checked);
std::println("+ 5j version correct: {}", plus_ok);
std::println("- 2j version correct: {} (negative results: {})", minus_ok, negative);
std::println("is_leap_year agrees with <chrono> for {} of 800 years", leap_ok);
std::println("2000-03-01 was a {}; 2100-03-01 will be a {}", names[zeller(2000, 3, 1)], names[zeller(2100, 3, 1)]);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra weekday.cpp -o weekday
./weekday
g++-16 -std=c++23 -Wall -Wextra weekday.cpp -o weekday
./weekday
""") Output
$ clang++ -std=c++23 -Wall -Wextra weekday.cpp -o weekday $ ./weekday days checked: 146097 + 5j version correct: 146097 - 2j version correct: 141421 (negative results: 4676) is_leap_year agrees with <chrono> for 800 of 800 years 2000-03-01 was a Wednesday; 2100-03-01 will be a Monday $ g++-16 -std=c++23 -Wall -Wextra weekday.cpp -o weekday $ ./weekday days checked: 146097 + 5j version correct: 146097 - 2j version correct: 141421 (negative results: 4676) is_leap_year agrees with <chrono> for 800 of 800 years 2000-03-01 was a Wednesday; 2100-03-01 will be a Monday
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 weekday_session.py
Step through both versions for the first day the program names, and watch the two sums part:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- The inputs. Day 1 of month 3 needs no shift: only months 1 and 2 count as 13 and 14 of the year before. The year 2000 splits into k = 2000 % 100 = 0 and j = 2000 / 100 = 20.
- One rank, from the left.
13 * (month + 1) / 5mixes*and/, which share a rank and group from the left: (13 × 4) / 5 = 52 / 5 = 10, with the .4 dropped. Grouped the other way, 4 / 5 would be 0, and so would the term. - The + 5j sum. day + 10 + k + k / 4 + j / 4 + 5 × j is 1 + 10 + 0 + 0 + 5 + 100 = 116, and 116 % 7 is 4.
- Index 4 is Wednesday. The program's list of names starts at Saturday, so index 4 is Wednesday: the day both builds printed.
- The - 2j sum. The same terms with - 2 × j give 1 + 10 + 0 + 0 + 5 - 40 = -24. In C++,
-24 % 7is -3, because the remainder takes the sign of its left operand. - No day has index -3. An array has no element -3. Adding 7 to -3 gives 4, the same Wednesday: the formula was right, and only the negative remainder spoiled it.
- 4,676 days of 146,097. Over the whole 400-year cycle the - 2j remainder came out negative on 4,676 days, and those were exactly the days that version got wrong: 146,097 − 4,676 = 141,421 right.
The + 5j version agrees with <chrono> on all 146,097 days, the length of the Gregorian calendar’s 400-year
cycle. The - 2j version is wrong on exactly the 4,676 days where its remainder came out negative, and right on all
the others, so the formula was never at fault: the remainder operator was. is_leap_year matches <chrono>’s
is_leap for all 800 years it was given. In your own code, prefer <chrono>’s calendar types to hand-written
formulas, and keep a formula like this one as an exercise in reading operators.
Checkpoint
Check: Remainders in a real formula
Practise: a clock that goes back past midnight
clock_check.cpp holds six checks for clock_add, which moves a time of day, counted in minutes after midnight,
forwards or backwards. Its one line uses % as if a remainder could never be negative, so three of the four checks
that go backwards fail:
// Exercise: clock_add(minute, delta) moves a time of day, counted in minutes after midnight (0 to 1439),
// by delta minutes, forwards or backwards. Finish it, then build and run this file: every check must say ok.
#include <print>
constexpr int minutes_per_day = 24 * 60;
int clock_add(int minute, int delta) {
return (minute + delta) % minutes_per_day; // right only while minute + delta is not negative
}
int failures = 0;
void check(int minute, int delta, int expected) {
const int got = clock_add(minute, delta);
std::println("{} clock_add({}, {}) = {}, expected {}", got == expected ? "ok " : "FAIL", minute, delta, got,
expected);
if (got != expected) ++failures;
}
int main() {
check(600, 45, 645); // later the same day
check(1430, 20, 10); // forwards past midnight
check(10, -20, 1430); // backwards past midnight
check(0, -1, 1439); // one minute before midnight
check(0, -minutes_per_day, 0); // a whole day back
check(720, -3 * minutes_per_day - 1, 719);
std::println("{} of 6 checks failed", failures);
return failures == 0 ? 0 : 1;
} Output (exit status 1)
ok clock_add(600, 45) = 645, expected 645 ok clock_add(1430, 20) = 10, expected 10 FAIL clock_add(10, -20) = -10, expected 1430 FAIL clock_add(0, -1) = -1, expected 1439 ok clock_add(0, -1440) = 0, expected 0 FAIL clock_add(720, -4321) = -721, expected 719 3 of 6 checks failed
Recorded with Apple clang version 21.0.0 (clang-2100.3.34.2) on macOS 26 arm64. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined clock_check.cpp -o clock_check && ./clock_check
- Copy
clock_check.cppand changeclock_addso that it always returns a minute from 0 to 1439. - Build and run it with the command under the program, or with
g++-16in place ofclang++. - You are done when every line starts with ok and the last line says 0 of 6 checks failed.
A first hint: the sum is negative only when the time goes back past midnight, and wrap_mod in the division program
handles exactly that case for any positive b.
When every check passes, test yourself on the five ideas of the lesson. Each question comes with feedback on every option, and the idea you are least sure of is asked first:
Practice that adapts to you
Practise this lesson
12 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What are -7 / 2 and -7 % 2 in C++, and why?
-7 / 2 is -3 and -7 % 2 is -1. Since C++11, integer division truncates towards zero, so the exact quotient -3.5
becomes -3, not -4. The remainder is defined so that (a / b) * b + a % b == a holds: -3 × 2 + (-1) = -7. As a
result the remainder always has the sign of the left operand, which differs from the mathematical convention of a
remainder from 0 to b − 1. When you need that, for example to wrap a negative value onto a clock or a ring of
indexes, compute r = a % b and add b when r is negative, or keep the values non-negative from the start.
An interviewer who hears that answer tends to probe the edges of the rule next. Pick an answer to each of these two, and the feedback says what every option gets right or misses:
Checkpoint
Interview round: two follow-up questions
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
Permissions are bits: READ is 1, WRITE is 2, EXEC is 4. A check reads if (flags & WRITE == WRITE) allow_write();. Which users does it let write, which does it refuse, and how would you write and protect the check?
-
Mid to senior
A ring buffer of size slots moves its read position backwards with pos = (pos - 1) % size;. With pos an int, it reads outside the buffer when pos is 0. With pos a std::size_t, it works when size is 16 but not when size is 10. Explain both, and step backwards correctly.
Key takeaways
- Precedence decides grouping:
*/%before+-, shifts, comparisons, the bitwise operators,&&,||, then?:and assignment. - Most operators group from the left; prefix operators,
?:and assignment group from the right. - Integer
/truncates towards zero and%takes the sign of the left operand:-7 / 2 == -3,-7 % 3 == -1. Write a floor division or a wrapping remainder when you need one. - Dividing by zero and
INT_MIN / -1are undefined behaviour. &&and||short-circuit, soi < v.size() && v[i] > 0is safe;&and|always evaluate both sides.x & 1 == 0meansx & (1 == 0), anda < b < cmeans(a < b) < c. Both compilers warn; Clang 21 rejects the chained comparison. Parenthesise when in doubt.
Terms in this lesson
- associativity
- The rule that groups a run of operators of equal precedence: from the left for most binary operators, so 20 - 6 - 4 is (20 - 6) - 4, and from the right for assignment and ?:, so x = y = 7 is x = (y = 7).
- precedence
- How tightly an operator holds its operands compared with other operators. * has a higher precedence than +, so a + b * c means a + (b * c). Precedence decides how an expression is grouped, not the order in which its operands are evaluated.
- short-circuit evaluation
- Evaluating the right operand of && or || only when the left one leaves the result open: in false && f() and in true || f(), f is never called. It lets a check guard the operand after it, as in i < v.size() && v[i] > 0.
Corrections
- The weekday section now says that the - 2j version fails on the 4,676 days where its remainder is negative: a negative sum that 7 divides leaves 0, the right answer.
References
- Working Draft, Programming Languages: C++ (N4950): [expr] Expressions, [expr.mul], [expr.log.and], [expr.log.or] (ISO/IEC JTC1/SC22/WG21)
- Options to Request or Suppress Warnings (-Wparentheses) (GNU Project)
- Clang 21.1.0 Release Notes (chained comparisons are an error by default) (LLVM Project)
- Diagnostic flags in Clang (LLVM Project)
- C++ Core Guidelines: ES.41, If in doubt about operator precedence, parenthesize (Standard C++ Foundation)
- Kalender-Formeln (Chr. Zeller, Acta Mathematica 9, 1887) (Acta Mathematica)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress