Reading history

Operator Precedence and Associativity in C (Table)

7 min read 4 views

Which C operator runs first? Full precedence table with associativity, worked examples, and six precedence traps behind real bugs.

When an expression has several operators, C needs rules to decide how to group them. Precedence says which operator binds tighter, like multiplication before addition. Associativity breaks ties between operators at the same level. Get these wrong and your code compiles, runs, and quietly gives the wrong answer.

In this lesson you will learn

  • How precedence decides grouping, with worked examples
  • When associativity is left-to-right and when it is right-to-left
  • The full C precedence table, grouped so it is easy to remember
  • Six precedence traps that cause real bugs
  • Why precedence does not decide the order functions are called

Precedence: Which Operator Binds Tighter

Just as in school maths, *, / and % bind tighter than + and -. Brackets override everything.

#include <stdio.h>

int main(void) {
    int price = 120, qty = 3, discount = 20;

    int a = price + qty * discount;        /* * before + */
    int b = (price + qty) * discount;      /* brackets first */
    int c = 100 / 5 % 3;                   /* same level: left to right */
    int d = 2 + 3 > 4;                     /* + before >, result is 1 (true) */

    printf("a = %d\n", a);
    printf("b = %d\n", b);
    printf("c = %d\n", c);
    printf("d = %d\n", d);
    return 0;
}

Output

a = 180
b = 2460
c = 2
d = 1
  • price + qty * discount is 120 + (3 * 20) = 180.
  • Brackets force the addition first: (120 + 3) * 20 = 2460.
  • / and % share a level, so they run left to right: (100 / 5) % 3 = 20 % 3 = 2.
  • Arithmetic binds tighter than comparison: (2 + 3) > 4 is true, which C stores as 1.

Associativity: Breaking Ties

When two operators have the same precedence, associativity decides the grouping. Most binary operators group left to right. Three kinds group right to left: unary operators, the conditional operator ?:, and all assignments.

#include <stdio.h>

int main(void) {
    int x, y, z;
    x = y = z = 7;                 /* right to left: z = 7, then y = z, then x = y */
    printf("x = %d, y = %d, z = %d\n", x, y, z);

    int marks = 72;
    const char *grade = marks >= 80 ? "A+" : marks >= 70 ? "A" : "B";   /* ?: groups right to left */
    printf("grade = %s\n", grade);

    int n = 20;
    n -= 4 * 2;                    /* compound assignment is done last */
    printf("n = %d\n", n);
    return 0;
}

Output

x = 7, y = 7, z = 7
grade = A
n = 12
  • x = y = z = 7 groups as x = (y = (z = 7)). An assignment produces the value it stored, so the 7 flows leftwards into all three.
  • The chained ?: groups as marks >= 80 ? "A+" : (marks >= 70 ? "A" : "B"), which reads like an if-else ladder.
  • n -= 4 * 2 means n = n - (4 * 2), because assignment operators are almost at the bottom of the table.

The C Precedence Table

Operators higher in the table bind tighter. Operators in the same row share a level.

LevelOperatorsGroupAssociativity
1 (tightest)a++ a-- f() a[i] s.m p->mPostfixLeft to right
2++a --a +a -a ! ~ (type) *p &a sizeofUnaryRight to left
3* / %MultiplicativeLeft to right
4+ -AdditiveLeft to right
5<< >>ShiftLeft to right
6< <= > >=RelationalLeft to right
7== !=EqualityLeft to right
8&Bitwise ANDLeft to right
9^Bitwise XORLeft to right
10|Bitwise ORLeft to right
11&&Logical ANDLeft to right
12||Logical ORLeft to right
13?:ConditionalRight to left
14= += -= *= /= %= <<= >>= &= ^= |=AssignmentRight to left
15 (loosest),CommaLeft to right

An easy way to remember it: things attached to a single value come first (postfix, then unary). Then arithmetic in maths order, then shifts. Then comparisons: first “bigger or smaller”, then “equal or not”. Then bit operators (AND, XOR, OR), then logical operators (AND, OR). The decision operator ?: comes next, then storing the result (assignment), and finally the comma.

Six Precedence Traps That Cause Real Bugs

Each line below compiles, and each one does something different from what it seems to say. Compiling with -Wall makes GCC warn about all three bracket problems in this program.

#include <stdio.h>

int main(void) {
    int flags = 6;                          /* binary 110 */
    int shift = 1 << 2 + 1;                 /* + before <<, so 1 << 3 */
    int bitcheck = flags & 4 == 4;          /* == before &, so flags & 1 */
    int fixed = (flags & 4) == 4;

    int a = 10, b = 20, c = 5;
    int chained = a < b < c;                /* (a < b) < c  ->  1 < 5 */

    printf("1 << 2 + 1        = %d\n", shift);
    printf("flags & 4 == 4    = %d\n", bitcheck);
    printf("(flags & 4) == 4  = %d\n", fixed);
    printf("10 < 20 < 5       = %d\n", chained);
    return 0;
}

Output

1 << 2 + 1        = 8
flags & 4 == 4    = 0
(flags & 4) == 4  = 1
10 < 20 < 5       = 1
  1. Shifts are looser than arithmetic. 1 << 2 + 1 is 1 << 3 = 8, not (1 << 2) + 1 = 5.
  2. Bitwise & is looser than ==. flags & 4 == 4 is flags & (4 == 4), which is flags & 1. Always write (flags & 4) == 4.
  3. Comparisons do not chain. 10 < 20 < 5 is (10 < 20) < 5, which is 1 < 5: true! Write a < b && b < c.
  4. = inside a condition. if (x = 5) stores 5 and is always true. You meant ==.
  5. *p++ moves the pointer, not the value. Postfix ++ binds tighter than *, so it reads *p and then advances p. To increment the value, write (*p)++.
  6. The comma has the lowest precedence of all. x = 1, 2; sets x to 1. Only x = (1, 2); sets it to 2.

sizeof and Pointer Operators

#include <stdio.h>

int main(void) {
    int i = 5;
    size_t s = sizeof(i++);        /* sizeof does not evaluate its operand */
    printf("sizeof gives %zu, i is still %d\n", s, i);

    int arr[] = {10, 20, 30};
    int *p = arr;
    int v = *p++;                  /* postfix ++ binds tighter than *: read, then move */
    printf("v = %d, now *p = %d\n", v, *p);
    return 0;
}

Output

sizeof gives 4, i is still 5
v = 10, now *p = 20

sizeof works out a size from the type of its operand at compile time, so i++ inside it never runs. (On most systems an int is 4 bytes.) The second line shows trap 5 in action: *p++ returned 10 and left p pointing at 20.

Precedence Is Not Evaluation Order

Precedence decides how an expression is grouped, not the order in which its parts are computed.

int total = read_price() + read_qty() * read_rate();

Precedence guarantees the result is read_price() + (read_qty() * read_rate()). It does not say which function is called first. The compiler may call them in any order. If each function prints something or reads input, the order can differ between compilers.

The same rule makes this line undefined behaviour: i = i++ + ++i;. It changes i more than once without a defined order, so there is no correct answer, and different compilers really do print different results. Never change the same variable twice in one expression.

Only four operators guarantee left-before-right evaluation: &&, ||, ?: and the comma operator. That is why if (p != NULL && p->age > 18) is safe: the right side only runs if the left side is true.

Best Practices

  • Add brackets whenever you mix bitwise, shift, logical and comparison operators. They cost nothing at run time.
  • Compile with -Wall -Wextra; GCC and Clang warn about most traps on this page.
  • Split long expressions into named steps. int subtotal = qty * rate; is clearer than a one-line formula.
  • Never modify a variable twice in the same expression.

Practice Exercises

Exercise 1. What is the value of 20 - 4 * 3 + 6 / 2?

Show answer

20 - 12 + 3 = 11. Multiplication and division first, then left to right.

Exercise 2. With int a = 0, b = 5;, what does a == 0 || b++ > 3 give, and what is b afterwards?

Show answer

The result is 1 (true). Because the left side of || is already true, the right side never runs, so b stays 5.

Exercise 3. Add brackets to show how C groups x = a > b ? a : b + 1;

Show answer

x = ((a > b) ? a : (b + 1)); The + 1 only applies to b.

Exercise 4. Fix this test so it checks whether bit 3 of status is set: if (status & 8 != 0)

Show answer

if ((status & 8) != 0). Without brackets it means status & (8 != 0), which tests bit 0.

Frequently Asked Questions

What is the difference between precedence and associativity?

Precedence decides grouping between operators at different levels. Associativity decides grouping between operators at the same level, either left to right or right to left.

Which operators in C are right-associative?

Unary operators (such as !, *p, ++a and casts), the conditional operator ?:, and all assignment operators.

Do brackets slow down a program?

No. Brackets only tell the compiler how to group the expression; they generate no extra instructions.

Why does a < b < c compile in C?

Because a < b produces the integer 0 or 1, which is then compared with c. It is legal but almost never what you mean.

Summary

  • Precedence decides which operators group first; brackets override it.
  • Associativity breaks ties; unary, ?: and assignment are right-to-left.
  • Watch the traps: shifts vs +, & vs ==, chained comparisons, *p++, and the comma.
  • Precedence does not fix evaluation order; never modify a variable twice in one expression.
  • When in doubt, add brackets and compile with -Wall.
Lessons are also marked complete when you click Next.