Skip to content
FollowtheDamnCode

Operator Precedence

Which operation happens first.

3 minute read

Big idea

When an expression has several operators, precedence decides which runs first — just like in school maths.

The idea

*, /, and % go before + and -:

int x = 2 + 3 * 4;   // 3 * 4 first → 2 + 12 → 14, not 20

When operators have the same precedence, C works left to right:

int y = 20 / 5 * 2;  // (20 / 5) * 2 → 4 * 2 → 8, not 20 / 10

Brackets beat everything. Whatever's inside ( ) happens first:

int z = (2 + 3) * 4; // 20
FirstThenLast
( )* / %+ -

(= comes after all of these — the right side is worked out fully, then stored.)

Predict: three expressions, three answers
#include <stdio.h>

int main(void) {
    printf("%d\n", 10 - 4 - 3);
    printf("%d\n", 10 - (4 - 3));
    printf("%d\n", 1 + 17 % 5 * 2);
    return 0;
}
What does it print? Show the answer
3
9
5

Run and edit it in the app.

The last one: % and * share a level, so left to right — 17 % 5 is 2, then 2 * 2 is 4, then 1 + 4 is 5.

Use brackets anyway

Even when you know the rules, brackets make your intent obvious to the next person (and to you, next month). (a * b) + c reads faster than a * b + c, and it can't be misread.

Fix the bug: the average should be 15
#include <stdio.h>

int main(void) {
    int a = 10, b = 20;
    int average = a + b / 2;
    printf("%d\n", average);
    return 0;
}
output
15

Run and edit it in the app.

Watch it

Think of it like

A recipe that says "add 2 eggs to the flour, then double everything". The order changes the result — so the recipe (and C) needs a rule about what happens first.

🕷️ Spidey-sense: Tony drilled me on this: in a fight, order matters. Web the hands, then the feet. In C, * and / go first, then + and - — and if you want a different order, wrap it in brackets.

Put the steps of 2 + 12 / (1 + 2) * 3 in the order C does them.

Key terms

  • Precedence — Which operators run first when there are several.
  • Associativity — The direction for operators with equal precedence; for arithmetic, left to right.
  • Parentheses — ( ), which force the part inside to run first.

Check yourself

What is 2 + 3 * 4?

What is 20 / 5 * 2?

What always runs first?