Loading lessons...
Operator Precedence
Operator Precedence
When several operators share one expression, C needs a rule for which one runs first. That rule is precedence.
Multiplication before addition
printf("%d\n", 2 + 3 * 4); // 14, not 20
printf("%d\n", (2 + 3) * 4); // 20
The usual order
From highest to lowest for the operators in this course:
*,/,%+,-==,!=,>,<,>=,<=&&, then||
Parentheses always win
If you ever feel unsure, put parentheses where you want. They override any default precedence:
printf("%d\n", (2 + 3) * 4); // 20
Associativity: same power, left to right
For operators with equal precedence, like a - b - c, C evaluates left to right: (a - b) - c.
TL;DR
- Precedence decides which operator runs first.
*,/,%come before+,-.- Comparisons come after those.
- Parentheses override everything; use them when unsure.