Concepts / Operator Precedence in C++

Operator Precedence in C++

Arithmetic operators (+, -, *, /, %) combine numeric values, and with integer operands the division truncates and the percent operator reports the remainder.

  • Programming

A Line of Output That Looks Wrong

Most of the work a C++ program does with numbers comes down to a handful of symbols placed between two values. Plus, minus, star, slash, and percent handle arithmetic. Double equals, the less-than sign, and their relatives handle comparison. Each line of a program asks the computer for one result and prints it. When a printed line surprises you, the cause is almost always a small mismatch between what you expected the operator to do and what it actually does with the operands you gave it.

What do you think happens?

If both a and b are int variables holding 7 and 2, what does a / b print?

  • 3.5

  • 3

  • 4

  • 3 remainder 1

Reveal answer
Answer:

3

Both operands are whole numbers, so the result is a whole number too. The fractional part is discarded, leaving 3.

Tracing Integer Division and Remainder

The source lists five binary arithmetic operators: plus for addition, minus for subtraction, multiply, divide, and the modulus operator for remainder. Each sits between two operands, as in x+y or x%y. Which operator you get and what it returns both depend on the types of the values on each side. The percent operator belongs to the integer world: it reports the remainder, or modulus, for integers.

Division is where most early surprises happen. When both operands are integers, the result is also an integer. The fractional portion is discarded, so the quotient is truncated toward zero. The remainder operator recovers the part that was thrown away. For positive operands, the two operators are linked by the relation below, where 3 is the quotient and 2 is the remainder. Keeping this relation in mind makes it much easier to predict what the percent operator will produce.

Formula
cpp
Output
3
1
Notes on the code
  • a / b: both operands are int, so the fractional part of 3.5 is discarded and the result is 3
  • a % b: the remainder that was discarded by the division is 1
  • 3 times 2 plus 1 gives back 7, the original value of a
7 / 2two int operandsQuotient: 3fraction 0.5 discardedRemainder: 1the part thrown awaydivisionpercent
How does 7 divided by 2 split into a truncated quotient and a remainder, and where does each part come from?
Worked example

Predicting 17 % 5 and 17 / 5

Predict the quotient and remainder when 17 is divided by 5, using integer operands.

  1. 1
    Find the quotient

    5 fits into 17 three full times, since 5 times 3 is 15 and 5 times 4 is 20 which is too large. So 17 / 5 gives 3.

  2. 2
    Find the remainder

    17 minus 15 leaves 2, so 17 % 5 gives 2.

  3. 3
    Check the relation

    The quotient times the divisor plus the remainder should equal the original value: 3 times 5 plus 2 is 17, which matches.

Result

17 / 5 produces 3 and 17 % 5 produces 2.

Comparisons Produce Answers, Not Numbers

Comparison operators do not produce a new number the way arithmetic does. They compare two values and report whether a relationship holds. The source lists six of them: equal (==), not equal (!=), less than (<), greater than (>), less than or equal (<=), and greater than or equal (>=). Because a comparison answers a yes-or-no question, its result is a truth value. The arithmetic operators, by contrast, take two numbers and return a new numeric value.

FeatureArithmetic operatorsComparison operators
Examples+, -, *, /, %==, !=, <, >, <=, >=
Question answeredWhat number do these values combine into?Does this relationship hold?
Typical resultA new numeric value such as 3 or 10A truth value, printed as 1 for true or 0 for false
Example with 7 and 27 / 2 gives 37 > 2 gives true

Arithmetic and comparison operators answer different kinds of questions

cpp
Output
1
9
Notes on the code
  • a > b asks whether 7 is greater than 2, and the printed 1 is the numeric representation of true
  • a + b produces a new number, 9
  • The parentheses group each expression so the statement prints one result per line
  • Common mistake

    Writing a single equals sign when you mean to compare

    What it looks like
    if (a = 5) instead of if (a == 5)
    Why it fails

    The source notes that equality uses a double equals sign, and a single equals sign is the assignment operator, a different job entirely.

    Do this instead
    Use == for the equality test and = only to store a value.
  • Common mistake

    Expecting a comparison to print the values being compared

    Why it fails

    A comparison reports whether a relationship holds, so its printed result is a truth value rather than either operand.

    Do this instead

    Print the operands separately if you need to see them, and print the comparison if you need the answer to the question.

How Bitwise Operators Work Bit by Bit

The source describes a group it calls logical operators and recommends separating it into two clearly different tools. One tool works on the individual bits inside a value. The other works on whole conditions and returns true or false. The bit-level operators are bitwise and (&), bitwise or (|), bitwise exclusive or (^), and bitwise complement (~). Bitwise operators act on each bit of their operands and return a result of the operand type.

Each bit position is combined on its own. For the & operator, the result bit is 1 only when both operands have a 1 in that position. For the | operator, the result bit is 1 when either operand has a 1 there. Consider 6 and 3. In binary, 6 is 110 and 3 is 011. Lining the positions up gives the following.

Bit 06: 0, 3: 1, result 0Bit 16: 1, 3: 1, result 1Bit 26: 1, 3: 0, result 0
When computing 6 & 3, which bit positions line up, and what is the result bit for each position?
Worked example

Computing 6 & 3 and 6 | 3

Find the result of 6 & 3 and 6 | 3 by combining bits position by position.

  1. 1
    Write the operands in binary

    6 is 110 and 3 is 011, with positions written from the highest bit on the left.

  2. 2
    Combine bitwise and

    Position 2: 1 and 0 gives 0. Position 1: 1 and 1 gives 1. Position 0: 0 and 1 gives 0. The result is 010, which is 2.

  3. 3
    Combine bitwise or

    Position 2: 1 or 0 gives 1. Position 1: 1 or 1 gives 1. Position 0: 0 or 1 gives 1. The result is 111, which is 7.

Result

6 & 3 produces 2, and 6 | 3 produces 7.

The bitwise exclusive or (^) returns 1 in a position only when exactly one of the two operands has a 1 there. The complement (~) flips each bit of a single operand. The source identifies these as the four bit-level operators and describes them as acting on each bit, so the position of each bit is what determines the outcome.

Bitwise Versus Logical Operators

Logical operators treat each whole operand as true or false, and they return true or false. The source lists two of them: logical and (&&) and logical or (||). Bitwise operators inspect the individual bits of the same values. This means the same numbers can produce very different results depending on which family you choose, and the two families are not interchangeable.

2 && 1both values nonzerotrue (1)whole values tested2 & 110 and 01 bit by bit0no position has 1 in bothtruebit by bit
Why does 2 && 1 produce true while 2 & 1 produces 0, given that the logical operators treat whole values as true or false?
cpp
Output
1
0
Notes on the code
  • 2 && 1 asks whether both whole values count as true, and the result is true, printed as 1
  • 2 & 1 combines bits: 10 and 01 share no position with a 1, so the result is 0

Tracing an Unexpected Output

When a program prints something you did not expect, locate the first line whose output differs from your prediction. Work through the statements one at a time, writing down the value of each variable as you go. Then check the operator family, the operand types, and the number of symbols in the expression. Most surprising outputs come from using the wrong family, the wrong operand type, or the wrong number of symbols.

  1. 1
    Write down the value of every variable before the first suspicious line.
  2. 2
    Identify the operator family: an arithmetic result is a number, a comparison result is true or false, and a bitwise result is built from bit positions.
  3. 3
    Check the operand types. If both are integers, expect a truncated quotient from division.
  4. 4
    Count the symbols. A single equals sign assigns, while a double equals sign compares.
  5. 5
    Compare the printed line against your prediction and stop at the first line that differs.
Debugging

Suppose a program prints 3 where the author expected 3.5 for a / b, with a and b both int. Tracing shows the operand types are the cause: both sides are whole numbers, so the division truncates. Converting one operand to a floating-point type would change the result family, but that is a separate topic and is not covered by the source here.

Predict Before You Run

MEDIUM

Without running anything, predict the printed value of 9 % 4. Then predict 5 & 4 and 5 | 4. Write your three answers down before checking.

Hints
  • Use the relation quotient times divisor plus remainder equals the original value: 9 equals 2 times 4 plus 1.
  • Write 5 as 101 and 4 as 100, then combine each bit position for the and and or operators.

What do you think happens?

What is 2 + 3 * 4 in a C++ expression with int operands?

  • 20

  • 14

  • 24

Reveal answer
Answer:

14

Multiplication is evaluated before addition, so 3 * 4 gives 12 and then 2 + 12 gives 14. Parentheses such as (2 + 3) * 4 change the grouping and produce 20.

Key Takeaways

  • Arithmetic operators combine numeric values, and with integer operands the division truncates while the percent operator reports the remainder.
  • For positive operands, the quotient times the divisor plus the remainder gives back the original value, which helps predict results of the percent operator.
  • Comparison operators answer yes-or-no questions and return truth values, and the double equals sign is the equality test rather than the single equals sign.
  • Bitwise operators act on each bit position and return a result of the operand type, while && and || combine whole conditions into true or false.
  • When an output surprises you, trace the statements one at a time and find the first line that diverges, checking operator family, operand types, and symbol count.

Related concepts

More concepts starting with O