Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 171 ยท Operators

Operator Precedence and the Conditional Operator

The full C++ operator precedence and associativity table, how evaluation order differs, the ?: conditional operator, the comma operator, sizeof and ::.

When an expression contains several operators, such as a + b * c > d && e, C++ needs rules to decide which operator gets which operands. Those rules are precedence (which operators bind tighter) and associativity (how operators of the same level group). Get them wrong in your head and the code does something other than what you read.

This lesson gives you the complete precedence table, explains the difference between precedence and evaluation order (they're not the same thing, and confusing them causes real bugs), and then covers four operators that don't fit anywhere else: the conditional operator ?:, the comma operator, sizeof and the scope resolution operator ::.

Precedence, associativity and evaluation order

Three separate ideas are at work in every expression:

  • Precedence decides how an expression is grouped. Because * binds tighter than +, 2 + 3 * 4 groups as 2 + (3 * 4).
  • Associativity decides the grouping when operators share a level. Subtraction is left-associative, so 10 - 4 - 3 is (10 - 4) - 3. Assignment is right-associative, so a = b = 0 is a = (b = 0).
  • Evaluation order decides when each operand is computed at run time. Precedence says nothing about it. In f() + g() * h(), the multiplication happens before the addition, but the three function calls may run in any order.

Parentheses override precedence and associativity. They don't change evaluation order.

The precedence table

From the tightest binding (top) to the loosest (bottom). Operators in the same row have the same precedence.

Level Operators Description Associativity
1 :: scope resolution left to right
2 a++ a-- f() a[i] . -> T() T{} postfix, call, subscript, member access, functional cast left to right
3 ++a --a +a -a ! ~ (T)a *p &x sizeof co_await new delete prefix and unary operators right to left
4 .* ->* pointer to member left to right
5 * / % multiplicative left to right
6 + - additive left to right
7 << >> bit shifts (and stream insertion/extraction) left to right
8 <=> three-way comparison (C++20) left to right
9 < <= > >= relational left to right
10 == != equality left to right
11 & bitwise AND left to right
12 ^ bitwise XOR left to right
13 | bitwise OR left to right
14 && logical AND left to right
15 || logical OR left to right
16 a ? b : c throw co_yield = += -= *= /= %= <<= >>= &= ^= |= conditional, throw, assignment right to left
17 , comma left to right

You don't need to memorize all of it. A useful mental shortcut: unary, then arithmetic, then shifts, then comparisons, then bitwise, then logical, then assignment, then comma. The one place where intuition fails is the bitwise operators &, ^ and |, which sit below the comparisons (a leftover from C). That's why x & 1 == 0 doesn't mean what it looks like.

C++ Precedence and associativity in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

1 << (a + 1) is 8. Without the parentheses, 1 << a + 1 means exactly the same thing, because addition binds tighter than shifting. GCC still warns about that version (suggest parentheses around '+' inside '<<'), and it is right to: many readers guess the grouping wrong. The parentheses cost nothing and remove the doubt.

Streams and precedence

The << operator does double duty as the output operator for std::cout, and it keeps the precedence of the shift operator. That's fine for arithmetic (std::cout << a + b prints the sum) but not for anything below level 7:

C++
std::cout << a & b;              // error: (std::cout << a) & b
std::cout << (a & b);            // OK
std::cout << x > 0 ? "yes" : "no";   // error: ((std::cout << x) > 0) ? ...
std::cout << (x > 0 ? "yes" : "no"); // OK

std::println doesn't have this problem, because every argument is a separate function argument.

Evaluation order is a different question

Precedence tells you that in f() + g() * h() the result of g() is multiplied by the result of h(). It doesn't say which function runs first. For most operators (+, *, ==, function arguments, and others), the order in which operands are evaluated is unspecified: the compiler may pick any order, and may pick differently in different places.

C++17 tightened this for a handful of operators. These now evaluate their left operand completely before their right operand:

  • &&, || (short-circuiting, always guaranteed), and the comma operator ,
  • a ? b : c (the condition first, then only one branch)
  • << and >>, so std::cout << f() << g() calls f before g
  • member access and subscripts: a.b, a->b, a[b], and the function in a call before its arguments

And for assignment a = b (and compound assignment), the right side is evaluated first.

C++ Precedence does not fix evaluation order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Whatever order this compiler happens to choose for the first line, the result is always 7. In the std::cout line, each value is traced just before it is printed, because every << finishes before the next operand is evaluated. If the functions have side effects that depend on each other, that's a bug: split the expression into separate statements so the order is explicit.

The conditional operator ?:

The conditional operator (often called the ternary operator because it has three operands) picks one of two values:

C++
condition ? value_if_true : value_if_false

The condition is evaluated first, then only the chosen branch is evaluated. Unlike an if statement, ?: is an expression, so it can appear where a statement can't: in an initializer, a function argument or a return statement. That makes it perfect for initializing a const variable from a condition.

C++ The conditional operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Some rules and advice:

  • The two branches must have a common type. cond ? 1 : 2.5 is a double, even when the condition picks 1. cond ? 42 : "none" doesn't compile, because there's no common type between int and a string literal.
  • When both branches are lvalues of the same type, the result is an lvalue, so you can assign to it (the low/high example). It's legal but rarely clearer than an if.
  • ?: has very low precedence, so in larger expressions wrap it in parentheses: total + (member ? 0 : fee). Without them, total + member ? 0 : fee means (total + member) ? 0 : fee.
  • Chains of ?: are right-associative, which is what makes the grade table work. More than one level is usually clearer as if/else if or a switch; see if, else if and else.

The comma operator

a, b evaluates a, throws its value away, then evaluates b, and the result is b. The left side is guaranteed to finish first. Its one common, legitimate use is in a for loop that updates two variables:

C++
for (int i = 0, j = n - 1; i < j; ++i, --j) {
    // i walks forward, j walks backward
}

Careful: the comma in int i = 0, j = n - 1 is not the comma operator, it separates two declarations. Commas between function arguments aren't the operator either. Only the one in ++i, --j is.

Elsewhere, the comma operator mostly produces confusing code. int x = (1, 2); sets x to 2 (and GCC warns that the left operand has no effect). A classic mistake is writing matrix[i, j] for a 2D access. In C++20 that use was deprecated, and in C++23 the brackets can take several arguments for types that support a multidimensional operator[] (such as std::mdspan), so it no longer means the comma operator at all.

sizeof

sizeof is an operator, not a function, and it yields the size in bytes of a type or an expression's type, as a std::size_t. It's evaluated at compile time:

  • For a type, parentheses are required: sizeof(int).
  • For an expression, they're optional: sizeof x works, though most people write sizeof(x).
  • The operand expression is not evaluated. sizeof(i++) doesn't increment i; the compiler only looks at the type.
C++ sizeof and the comma in a for loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

sizeof(char) is 1 by definition, and the other sizes depend on the platform (on our server, int is 4 bytes and double 8). Fundamental Data Types lists the guarantees. sizeof on arrays and classes has its own surprises, covered in C-Style Arrays and Memory Layout.

The scope resolution operator ::

:: binds tighter than anything else. It picks a name out of a particular scope:

  • A namespace: std::println means "the println declared in namespace std". See Namespaces.
  • A class: std::string::npos, or Counter::count for a static member. You'll meet it constantly in Classes and Objects when defining member functions outside a class.
  • A scoped enum: Color::Red.
  • The global scope: a leading :: with nothing before it, as in ::total, reaches a global name even when a local variable has the same name.
C++ Choosing a scope with ::

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Shadowing a global like this is legal but confusing; Scope, Lifetime and Storage Duration explains why you should avoid it. std::string::npos is the "not found" value you'll use in String Methods.

Rules of thumb

  • Rely on precedence only for the obvious cases: arithmetic, comparisons combined with &&/||, and assignment.
  • Always parenthesize: bitwise operators next to comparisons, && mixed with ||, shifts next to arithmetic, and ?: inside larger expressions or after <<.
  • Never write an expression whose result depends on evaluation order. Modify a variable at most once per expression (Assignment and Increment Operators explains why).
  • Prefer clarity over cleverness: a temporary variable with a good name beats a one-liner nobody can parse.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::println("{}", 2 + 3 * 4 - 1); print?

    • binds tighter: 3 * 4 = 12, then left to right 2 + 12 - 1 = 13.
  2. 2. In int r = f() + g() * h();, what does C++ guarantee?

    Precedence fixes the grouping, not the evaluation order. The three calls may happen in any order.
  3. 3. What is the type of flag ? 1 : 2.5 when flag is true?

    The type of a conditional expression is decided at compile time from both branches. int and double have the common type double, so the result is 1.0.
  4. 4. After int i = 5; auto s = sizeof(i++);, what is i?

    The operand of sizeof is never evaluated; only its type matters. i stays 5.
  5. 5. Which line declares two variables rather than using the comma operator?

    Commas in a declaration separate declarators. Only expressions like (a, b) and ++i, --j use the comma operator.

Summary

  • Precedence decides grouping, associativity decides grouping within a level, and evaluation order is a separate, often unspecified, question.
  • Rough order from tight to loose: ::, postfix, unary, * / %, + -, shifts, <=>, relational, equality, & ^ |, &&, ||, then ?: and assignment, then the comma.
  • Bitwise operators bind more loosely than comparisons, and << on streams keeps shift precedence: parenthesize.
  • C++17 guarantees left-to-right evaluation for &&, ||, ,, ?:, <<, >>, ., -> and [], and right-before-left for assignment.
  • ?: is an expression that evaluates only one branch; both branches must share a common type.
  • The comma operator evaluates left then right and yields the right; use it only in for loop updates.
  • sizeof is a compile-time operator whose operand isn't evaluated; :: selects a name from a namespace, class, enum or the global scope.

Next: Strings with std::string, where you'll start working with text in C++.