Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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

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:

grouping.cpp C++ · grouping.cpp
#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);
}
How each expression is grouped Python · grouping_session.py
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:

Interactive · step by step How the compiler groups four lines of grouping.cpp Step through four expressions of the program. Each step shows which operands one operator takes, and the value the program printed.
How the compiler groups four lines of grouping.cpp, step 6 of 6. Showing a + b * c, a + (b * c), 20 - 6 - 4, (20 - 6) - 4, x = y = 7, x = (y = 7), a > b || b < c && c > 9 (false || true && false), false.a + b * ca = 2, b = 3, c = 4a + (b * c)printed 1420 - 6 - 4two minus signs(20 - 6) - 4printed 10x = y = 7two assignmentsx = (y = 7)both become 7a > b || b < c && c > 9false || true && falsefalse(a > b) || (b < c && c > 9)

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. * before +. In a + b * c the * has the higher precedence, so it takes b and c: 3 × 4 = 12, then 2 + 12 = 14. The program printed 14, and 20 for (a + b) * c.
  2. Equal ranks, from the left. 20 - 6 - 4 holds 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.
  3. Assignment, from the right. x = y = 7 groups from the right: y = 7 comes first, and its result, 7, is stored in x. The next line, x += y *= 2, doubles y to 14 and adds it to x, so the program printed x = 21, y = 14.
  4. 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 > b is false, b < c true and c > 9 false.
  5. && 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.
  6. 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

  1. Question 1 of 2 What is the value of r?

    Read the code, then choose one answer.

    int r = 2 + 3 * 4 - 6 / 2;
    A hint

    Find the two operators of the highest rank first, then work from the left.

    Show the answer: Question 1 of 2

    Answer: 11

    • and / bind more tightly than + and -, so this is 2 + 12 - 3, and + and - group from the left: (2 + 12) - 3 = 11.
  2. Question 2 of 2 How is 1 << n + 1 grouped?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 1 << (n + 1)

    The shift operators bind less tightly than + and -, so the addition happens first. Both compilers suggest parentheses here, Clang with -Wshift-op-parentheses and GCC with -Wparentheses, because readers often expect the other grouping.

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:

division.cpp C++ · division.cpp
#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));
}
Division and remainder with every sign Python · division_session.py
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:

Interactive · step by step Where -7 / 2 and -7 % 2 come from Step through one division with a negative left operand. The left column is what C++ computes, the right one the rounded-down pair that floor_div and wrap_mod produce.
Where -7 / 2 and -7 % 2 come from, step 5 of 5. Showing -7 / 2 (towards zero: -3), floor_div(-7, 2) (rounded down: -4), -7 % 2 ((-3) × 2 + (-1) = -7), remainder with -4 ((-4) × 2 + 1 = -7), -7 % 3 (-1: below the range), wrap_mod(-7, 3) (-1 + 3 = 2). In focus: -7 % 3, wrap_mod(-7, 3).-7 / 2towards zero: -3floor_div(-7, 2)rounded down: -4-7 % 2(-3) × 2 + (-1) = -7remainder with -4(-4) × 2 + 1 = -7-7 % 3-1: below the rangewrap_mod(-7, 3)-1 + 3 = 2

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. 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.
  2. Towards zero. C++ drops the fraction towards zero, so -7 / 2 is -3, as both builds printed. floor_div rounds down instead and returns -4.
  3. The remainder that fits. % gives the remainder that makes (a / b) * b + a % b equal a: (-3) × 2 + r = -7, so r is -1. Its sign is the sign of -7, the left operand.
  4. 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.
  5. Back into range. -7 % 3 is -1, which is no position on a clock of 3. wrap_mod adds 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

  1. Question 1 of 2 What is the value of -17 % 5?

    Type a number.

    A hint

    Divide first, truncating towards zero, then find the remainder that rebuilds -17.

    Show the answer: Question 1 of 2

    Answer: -2

    -17 / 5 is -3, the exact -3.4 truncated towards zero, and (-3) × 5 + r = -17 gives r = -2. The remainder has the sign of -17, the left operand.

  2. Question 2 of 2 Which test is true for every odd int n, negative values included?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: n % 2 != 0

    The remainder of an odd number divided by 2 is 1 for a positive one and -1 for a negative one, as the row for -7 and 2 showed. Only a test against 0 covers both.

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.:

short_circuit.cpp C++ · short_circuit.cpp
#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);
}
Which operands are evaluated Python · short_circuit_session.py
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:

Interactive · step by step The index check that protects v[i] Step through the condition of the if with i = 5 and a vector of two values. Watch which operand of && runs, and which never does.
The index check that protects v[i], step 4 of 4. Showing i < v.size() (false: 5 < 2 fails), v[i] > 0 (unchecked: undefined), prints positive, the else line. In focus: v[i] > 0.truetruefalsefalsei < v.size()false: 5 < 2 failsv[i] > 0unchecked: undefinedprints positiveboth operands truethe else lineprints the index message

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. The left operand first. && always evaluates its left operand first. i is 5 and v holds 2 values, so i < v.size() is false.
  2. && stops. false && anything is false, so && returns false without evaluating its right operand. v[i] > 0 never runs, and v[5], past the end of the vector, is never read.
  3. 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.
  4. 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

  1. Question 1 of 2 check() is the function of short_circuit.cpp: it prints "evaluating" and its name, then returns its second argument. What does this line print?

    Read the code, then choose one answer.

    bool r = check("A", true) || check("B", true);
    Show the answer: Question 1 of 2

    Answer: evaluating A, and nothing more

    || evaluates its left operand first and stops when it is true, as the program showed for "true || B". A check() on the right runs only when the left one returned false.

  2. Question 2 of 2 v is a std::vector<int> that may be empty. Which condition never reads an element that is not there?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: !v.empty() && v[0] > 0

    A guard protects only the operand to its right, and only with && or ||. Put the check first: when it settles the result, the read never happens.

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:

Two parse trees: x & 1 == 0 groups as x & (1 == 0) and is always false; (x & 1) == 0 tests whether x is even.written: x & 1 == 0parsed as x & (1 == 0)&x==10always falsemeant: (x & 1) == 0true for every even x==&0x1the parity test

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.

Two expressions that do not mean what they say

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);
}
What each compiler does with them Python · traps_session.py
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.

Programmer Calculator (Bitwise) Try x & 1 on a few numbers in binary to see why the lowest bit decides odd or even.

Checkpoint

Check: Groupings that mislead

  1. Question 1 of 2 x is 6. What is the value of even?

    Read the code, then choose one answer.

    bool even = x & 1 == 0;
    Show the answer: Question 1 of 2

    Answer: false

    == binds more tightly than &, so the expression is x & (1 == 0), which is x & 0, which is 0 for every x. Both compilers warn with -Wall; write (x & 1) == 0.

  2. Question 2 of 2 GCC builds bool b = 5 > 3 > 1; with a warning. What value does b hold?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: false

    A chained comparison groups from the left like any run of equal operators, so the second > compares a bool, promoted to 0 or 1, with 1. To test both bounds, write 5 > 3 && 3 > 1.

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:

weekday.cpp C++ · weekday.cpp
#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)]);
}
Checking 146,097 days Python · weekday_session.py
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:

Interactive · step by step One weekday, worked out with + 5j and with - 2j Step through Zeller's congruence for the first day the program names. The left column is the version that agreed on every day, the right one the version often printed with - 2j.
One weekday, worked out with + 5j and with - 2j, step 7 of 7. Showing day 1, month 3 (year 2000: k = 0, j = 20), 13 * (month + 1) / 5 ((13 × 4) / 5 = 10), the sum with + 5j, the sum with - 2j, 116 % 7 (gives 4), -24 % 7 (gives -3), names[4] (Wednesday), names[-3] (no such element).day 1, month 3year 2000: k = 0, j = 2013 * (month + 1) / 5(13 × 4) / 5 = 10the sum with + 5j1 + 10 + 0 + 0 + 5 + 100the sum with - 2j1 + 10 + 0 + 0 + 5 - 40116 % 7gives 4-24 % 7gives -3names[4]Wednesdaynames[-3]no such element

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. 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.
  2. One rank, from the left. 13 * (month + 1) / 5 mixes * 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.
  3. 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.
  4. Index 4 is Wednesday. The program's list of names starts at Saturday, so index 4 is Wednesday: the day both builds printed.
  5. The - 2j sum. The same terms with - 2 × j give 1 + 10 + 0 + 0 + 5 - 40 = -24. In C++, -24 % 7 is -3, because the remainder takes the sign of its left operand.
  6. 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.
  7. 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.

Day of the Week Calculator Check a few dates by hand against the weekday the program computes.

Checkpoint

Check: Remainders in a real formula

  1. Question 1 of 2 Which of these years does is_leap_year from weekday.cpp report as leap years?

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • 2000
    • 1996

    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0: 1996 passes the left side, 2000 the right side, and the century years 1900 and 2100 pass neither. The program checked 800 years against <chrono> and agreed on all of them.

  2. Question 2 of 2 For year 2100, month 3, day 1, the - 2j sum in zeller_minus is -26. What does -26 % 7 give in C++?

    Type a number.

    A hint

    -26 / 7 truncates towards zero first.

    Show the answer: Question 2 of 2

    Answer: -5

    -26 / 7 is -3, the exact -3.71 truncated towards zero, and (-3) × 7 + r = -26 gives r = -5. Adding 7 gives 2, Monday in the program's list, the day the + 5j version printed.

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:

The checks against the unfinished clock_add() C++ · clock_check.cpp
// 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

  1. Copy clock_check.cpp and change clock_add so that it always returns a minute from 0 to 1439.
  2. Build and run it with the command under the program, or with g++-16 in place of clang++.
  3. 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.

  1. Question 1 of 12 What are a and b afterwards?

    Read the code, then choose one answer.

    int a, b;
    a = b = 5;
    a += b *= 2;
    Show the answer: Question 1 of 12

    Answer: a is 15, b is 10

    Assignments group from the right: a = (b = 5) sets both to 5, and a += (b *= 2) doubles b to 10 and then adds that to a.

  2. Question 2 of 12 How does C++ group c > 3 ? 1 : 0 + 10?

    Choose one answer.

    Show the answer: Question 2 of 12

    Answer: c > 3 ? 1 : (0 + 10)

    The conditional operator binds less tightly than + and the comparisons, so the expression is (c > 3) ? 1 : (0 + 10). With c = 4 the program printed 1.

  3. Question 3 of 12 Why does std::cout << a & b; fail to compile when a and b are ints?

    Choose one answer.

    Show the answer: Question 3 of 12

    Answer: << ranks above &, so it is (std::cout << a) & b, which applies & to the stream

    When << writes to a stream it keeps its rank, above the bitwise operators and the comparisons. Write std::cout << (a & b) to print the bitwise AND.

  4. Question 4 of 12 What do these two expressions give?

    Read the code, then choose one answer.

    -7 / 2
    -7 % 2
    Show the answer: Question 4 of 12

    Answer: -3 and -1

    Integer division truncates towards zero, so -3.5 becomes -3, and the remainder makes (a / b) * b + a % b equal a: -3 × 2 + (-1) = -7. The remainder takes the sign of the left operand.

  5. Question 5 of 12 What does floor_div(7, -2) from division.cpp return?

    Type a number.

    A hint

    The exact quotient is -3.5. Which way does floor_div round?

    Show the answer: Question 5 of 12

    Answer: -4

    7 / -2 truncates to -3, but the division is inexact and the signs differ, so floor_div subtracts 1: -4, the value the program printed in the row for 7 and -2.

  6. Question 6 of 12 What does wrap_mod(-17, 5) from division.cpp return?

    Type a number.

    A hint

    Work out -17 % 5 first, then apply the correction.

    Show the answer: Question 6 of 12

    Answer: 3

    -17 % 5 is -2, which is negative, so wrap_mod adds 5 and returns 3: the position from 0 to 4 that -17 lands on.

  7. Question 7 of 12 Why is if (i < v.size() && v[i] > 0) safe when i may be past the end of v?

    Choose one answer.

    Show the answer: Question 7 of 12

    Answer: && evaluates v[i] > 0 only if i < v.size() is true

    && is evaluated from left to right and stops as soon as the result is known. With the operands swapped, v[i] would be read before the check, which is undefined behaviour for an index past the end.

  8. Question 8 of 12 With check() from short_circuit.cpp, what does this line print?

    Read the code, then choose one answer.

    bool r = check("A", false) & check("B", true);
    Show the answer: Question 8 of 12

    Answer: Both lines, evaluating A and evaluating B

    Only && and || skip an operand. & and | always evaluate both, which is why Apple clang warns that a & between two bool values was probably meant to be &&.

  9. Question 9 of 12 x is 7. What do the two lines give?

    Read the code, then choose one answer.

    bool a = (x & 1) == 0;
    bool b = x & 1 == 0;
    Show the answer: Question 9 of 12

    Answer: a is false, b is false

    The parenthesised test asks for the lowest bit and compares it with 0; the other compares 1 with 0 first and ands x with the result, 0.

  10. Question 10 of 12 Which condition tests that mid lies strictly between low and high?

    Choose one answer.

    Show the answer: Question 10 of 12

    Answer: low < mid && mid < high

    C++ has no chained comparisons: each comparison gives a bool, and the next one compares that bool. Join the two tests with &&.

  11. Question 11 of 12 Why are the parentheses there in (year % 4 == 0 && year % 100 != 0) || year % 400 == 0?

    Choose one answer.

    Show the answer: Question 11 of 12

    Answer: For the reader, and to silence -Wparentheses: && already binds more tightly than ||

    The parentheses show the rule's structure, divisible by 4 and not a century, or divisible by 400, and they silence the warning both compilers give for an && inside an ||.

  12. Question 12 of 12 With month = 13, what is 13 * (month + 1) / 5 in C++?

    Type a number.

    A hint

    * and / share a rank. Which one runs first?

    Show the answer: Question 12 of 12

    Answer: 36

    • and / group from the left: (13 × 14) / 5 = 182 / 5 = 36, with the .4 dropped by integer division. Grouped the other way, 14 / 5 would be 2 and the term 26.

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

  1. Question 1 of 2 Follow-up: "Write me an int division that rounds down, so that -7 divided by 2 gives -4." Which answer is right for every sign?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Compute q = a / b, then subtract 1 when a % b is not 0 and a and b have different signs

    floor_div in division.cpp takes the truncated quotient and corrects it by one when the division is inexact and the signs differ; the program printed -4 for -7 and 2 and for 7 and -2, and 3 for -7 and -2.

  2. Question 2 of 2 Follow-up: "Which of these int divisions is undefined behaviour?"

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: INT_MIN / -1

    Division by zero and INT_MIN / -1 are the two undefined divisions of ints. Every other quotient fits, and the truncation rule fixes its value.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. 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?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

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 / -1 are undefined behaviour.
  • && and || short-circuit, so i < v.size() && v[i] > 0 is safe; & and | always evaluate both sides.
  • x & 1 == 0 means x & (1 == 0), and a < b < c means (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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.