Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 135 ยท Operators

Operator Precedence, the Ternary and Comma Operators

The full C operator precedence and associativity table, grouping vs evaluation order, the ternary ?: and comma operators, sizeof, and common precedence bugs.

When an expression contains several operators, C has to decide which ones go together. Is a + b * c the same as (a + b) * c? Does *p++ increment the pointer or the value it points to? Does x & 1 == 0 test whether x is even? The answers come from two rules: precedence, which says which operators bind more tightly, and associativity, which says how operators of the same level group.

This lesson gives you the complete table for C, explains the difference between grouping and evaluation order (a common source of confusion), and introduces three operators that haven't had a lesson of their own yet: the conditional operator ?:, the comma operator and sizeof. It ends with the precedence bugs that experienced C programmers still write, and how to avoid them.

Precedence and associativity

Precedence decides which operator gets its operands first. Multiplication has higher precedence than addition, so 2 + 3 * 4 groups as 2 + (3 * 4), which is 14.

Associativity decides the grouping when operators share a level. Most binary operators are left-associative: 20 - 5 - 3 is (20 - 5) - 3, which is 12, not 20 - (5 - 3). Unary operators, the conditional operator and assignment are right-associative: a = b = 0 is a = (b = 0), and -~x is -(~x).

The full precedence table

From the tightest-binding operators (level 1) to the loosest (level 15):

Level Operators Description Associativity
1 x() x[] . -> x++ x-- (type){...} call, index, member access, postfix increment, compound literal left to right
2 ++x --x +x -x ! ~ (type) *p &x sizeof alignof prefix and unary operators, cast, dereference, address-of right to left
3 * / % multiplicative left to right
4 + - additive left to right
5 << >> shifts left to right
6 < <= > >= relational left to right
7 == != equality left to right
8 & bitwise AND left to right
9 ^ bitwise XOR left to right
10 | bitwise OR left to right
11 && logical AND left to right
12 || logical OR left to right
13 ?: conditional right to left
14 = += -= *= /= %= <<= >>= &= ^= |= assignment right to left
15 , comma left to right

(alignof is a C23 keyword; earlier standards spell it _Alignof. The standard itself defines precedence through its grammar rather than a table, but this table matches that grammar.)

You don't need to memorize all fifteen rows. A few landmarks cover nearly every real expression:

  • Postfix operators (a[i], f(), s.x, p->x, i++) bind tightest; then come the unary prefix operators.
  • Arithmetic follows school rules, and shifts come after + and -.
  • Comparisons come next, then the bitwise & ^ |, then the logical && before ||.
  • ?:, then assignment, then the comma, bind loosest.
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 scanf or fgets), it gets the next line from this box.

The 1 << 2 + 1 line is written with explicit parentheses in the code, because GCC would otherwise warn suggest parentheses around '+' inside '<<'. That warning is a good hint: when an expression needs the table to be understood, add the parentheses.

Grouping is not evaluation order

Precedence tells you how an expression is grouped, not in which order its parts are computed. In f() + g() * h(), the multiplication groups with g() and h(), but C doesn't say which of the three functions is called first. The compiler may call h before f.

Only four operators promise an order: &&, ||, ?: and the comma operator each evaluate their left (first) operand completely before the rest. Everywhere else the order is unspecified, and modifying a variable twice in one expression is undefined behavior, as you saw in Assignment and Increment Operators. If the order of side effects matters, put them in separate statements.

The conditional operator ?:

condition ? a : b is C's only ternary operator, with three operands. It evaluates the condition, then evaluates and yields either a (when the condition is nonzero) or b, never both. It's an expression, so you can use it inside other expressions, where an if statement can't go:

C
const char *label = count == 1 ? "item" : "items";
int larger = a > b ? a : b;
printf("%s\n", is_admin ? "welcome, admin" : "welcome");

Since ?: is right-associative, you can chain it for a short list of choices; the formatting below makes the structure visible. For anything longer, use if/else if (see if, else if and else).

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 scanf or fgets), it gets the next line from this box.

Two details to remember:

  • The result type comes from both operands. If one is an int and the other a double, the result is a double even when the int side is chosen, which is why the example prints 1.000000 and sizeof reports 8.
  • Low precedence. ?: binds more loosely than almost everything, so x + flag ? 1 : 0 means (x + flag) ? 1 : 0. Put parentheses around a conditional expression that sits inside a larger one: x + (flag ? 1 : 0).

The comma operator

The comma operator evaluates its left operand, throws the value away, then evaluates the right operand, which becomes the result. The left side is finished, including side effects, before the right side starts.

You'll mostly see it in for loops that update two variables at once:

C
for (int left = 0, right = n - 1; left < right; left++, right--) {
    // swap a[left] and a[right] ...
}

The comma in left++, right-- is the comma operator. The comma in int left = 0, right = n - 1 is not: in declarations, function calls (printf("%d", x)) and initializer lists, commas are plain separators with no ordering guarantee. Because the comma has the lowest precedence of all, x = 1, 2; means (x = 1), 2; and stores 1. Outside for headers, separate statements are clearer; the comma operator mostly appears in macros.

C The comma operator 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 scanf or fgets), it gets the next line from this box.

The x = (1, 2, 3) line exists only to show the rule; GCC warns that the left-hand operands have no effect, which is exactly why real code doesn't write it.

sizeof is an operator

sizeof gives the size, in bytes, of a type or an expression, as a size_t (print it with %zu). It's an operator, not a function, which has three consequences:

  • With an expression, the parentheses are optional: sizeof x, sizeof *p, sizeof arr[0]. With a type name they're required: sizeof(int).
  • It's a unary operator at level 2, so sizeof x + 1 means (sizeof x) + 1.
  • Its operand is not evaluated (except for variable-length arrays). sizeof i++ doesn't change i; the compiler only looks at the type.

The sizeof *p idiom, used with malloc, relies on this: it gives the size of what p points to without touching the pointer, as you'll see in Dynamic Memory.

Precedence bugs to recognize

These expressions all compile, and all do something other than what they seem to say:

You write C reads it as What you probably meant
x & 1 == 0 x & (1 == 0) (x & 1) == 0
a << 1 + b a << (1 + b) (a << 1) + b
*p++ *(p++) (correct for "read, then advance")
*p.field *(p.field) (*p).field, better p->field
!x == y (!x) == y !(x == y), better x != y
a || b && c a || (b && c) add parentheses either way
c = getchar() != EOF c = (getchar() != EOF) (c = getchar()) != EOF
flag ? 1 : 0 + x flag ? 1 : (0 + x) (flag ? 1 : 0) + x
C Two classic precedence bugs

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 scanf or fgets), it gets the next line from this box.

*p++ is a deliberate C idiom: read the current element and advance the pointer, which you'll use when walking through arrays and strings in Pointer Arithmetic. If you want the pointed-to value incremented instead, write (*p)++.

GCC's -Wall catches most of the table above under -Wparentheses. Compile with warnings on, and when the compiler suggests parentheses, add them. The best rule is the simplest: if a reader would have to look up the table to understand an expression, add parentheses or split it into two statements.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf("%d", 2 + 3 * 4 - 6 / 2); print?

    • and / are applied first: 3 * 4 is 12 and 6 / 2 is 3. Then left to right: 2 + 12 - 3 is 11.
  2. 2. With int a[] = {5, 9}; int *p = a;, what does int v = *p++; do?

    Postfix ++ binds tighter than unary *, so the expression is *(p++): it dereferences the old pointer value (5) and advances p.
  3. 3. What is the type of the expression flag ? 1 : 2.0?

    The result type of ?: is determined by both operands using the usual arithmetic conversions, so it is always double here.
  4. 4. After int x; x = 4, 8;, what is x?

    The comma operator has the lowest precedence, so the statement is (x = 4), 8; and the 8 is evaluated and discarded.
  5. 5. With int i = 1;, what is i after size_t s = sizeof i++;?

    sizeof only needs the type of its operand, so the expression is not evaluated (variable-length arrays are the one exception).

Summary

  • Precedence decides grouping between levels; associativity decides grouping within a level. Most binary operators group left to right; unary, ?: and assignment group right to left.
  • Landmarks: postfix > unary > arithmetic > shifts > comparisons > bitwise & ^ | > && > || > ?: > assignment > comma.
  • Grouping is not evaluation order. Only &&, ||, ?: and the comma operator guarantee their left operand is evaluated first.
  • cond ? a : b evaluates only one of a and b; its type comes from both. Parenthesize it inside larger expressions.
  • The comma operator evaluates left then right and yields the right; commas in declarations and calls are just separators.
  • sizeof is an operator: it doesn't evaluate its operand and returns a size_t.
  • When in doubt, add parentheses: (x & 1) == 0, (*p)++, (c = getchar()) != EOF.

Next: if, else if and else