In C programming, Operator Precedence determines the order in which operators are evaluated in an expression. When an expression contains multiple operators, the one with "higher precedence" is executed first.
Associativity comes into play when two operators of the same precedence level appear in the same expression. It defines whether the expression is evaluated from Left-to-Right or Right-to-Left.
Precedence: Think of this as the "Priority" level. For example, in the expression $10 + 5 * 2$, the multiplication ($*$) has higher precedence than addition ($+$), so the result is $20$, not $30$.
Associativity: If we have $10 / 5 * 2$, both / and * have the same precedence. Since their associativity is Left-to-Right, the division happens first: $(10 / 5) * 2 = 4$.
The table below lists C operators from highest precedence (1) to lowest precedence (15).
| Precedence | Operator Type | Operators | Associativity |
| 1 | Postfix | (), [], ->, ., ++, -- | Left-to-Right |
| 2 | Unary | +, -, !, ~, ++, --, (type), *, &, sizeof | Right-to-Left |
| 3 | Multiplicative | *, /, % | Left-to-Right |
| 4 | Additive | +, - | Left-to-Right |
| 5 | Shift | <<, >> | 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 | ` | ` |
| 11 | Logical AND | && | Left-to-Right |
| 12 | Logical OR | ` | |
| 13 | Conditional | ?: | Right-to-Left |
| 14 | Assignment | =, +=, -=, *=, /=, etc. | Right-to-Left |
| 15 | Comma | , | Left-to-Right |
Rule of Parentheses: You can always override precedence by using parentheses (). Expressions inside parentheses are always evaluated first.
Prefix vs Postfix: While both increment ++ and decrement -- have high precedence, postfix operators are evaluated before prefix operators.
Assignment Logic: Assignment is one of the few operators that works Right-to-Left. This allows for "Chained Assignments" like a = b = c = 10;.
Logical Operators: Logical AND (&&) has higher precedence than Logical OR (||). This is a frequent source of logic errors in complex if statements.
#include <stdio.h> int main() { int a = 20, b = 10, c = 15, d = 5; int result; // Example 1: Multiplicative over Additive // (20 + (10 * 15) / 5) -> (20 + 150 / 5) -> (20 + 30) result = a + b * c / d; printf("Result of a + b * c / d : %d\n", result); // Example 2: Using Parentheses to change order // ((20 + 10) * (15 / 5)) -> (30 * 3) result = (a + b) * (c / d); printf("Result of (a + b) * (c / d) : %d\n", result); // Example 3: Relational and Logical // ((20 > 10) && (15 < 5)) -> (1 && 0) -> 0 result = a > b && c < d; printf("Result of a > b && c < d : %d\n", result); return 0; }
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION