Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are evaluated in expressions. Precedence specifies which operator is evaluated first when multiple operators are present, while Associativity defines the order of evaluation for operators with the same precedence.
Here is a table of operators in order of Precedence:
Precedence | Operators | Description | Associativity |
---|---|---|---|
1 (Highest) | () [] -> . | Function call, array subscript, member access | Left-to-right |
1 (Highest) | ++ -- | Post-increment, post-decrement | Left-to-right |
2 | + - ! ~ * & sizeof | Unary operators, sizeof | Right-to-left |
2 | ++ -- | Pre-increment, pre-decrement | Right-to-left |
2 | (type) | Type cast | Right-to-left |
3 | * / % | Multiplication, division, modulus | Left-to-right |
4 | + - | Addition, subtraction | Left-to-right |
5 | << >> | Bitwise shift | Left-to-right |
6 | < <= > >= | Relational operators | Left-to-right |
7 | == != | Equality operators | 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 | ? : | Ternary conditional | Right-to-left |
14 | =, +=, -=, *= , /=, %=, <<=, >>=, &= , ^=, ` | Assignment operators | Right-to-left |
15 (Lowest) | , | Comma | Left-to-right |
Associativity
Associativity determines the direction in which operators of the same precedence level are evaluated:
- Left-to-right: Most operators (e.g., +, -, *, /, etc.) are evaluated from left to right.
- Right-to-left: Some operators like assignment (=) and unary operators (++, --, sizeof, etc.) are evaluated from right to left.
Examples:
1. Precedence
#include <stdio.h>
int main() {
int x = 5 + 2 * 3; // Multiplication (*) has higher precedence than addition (+).
printf("x = %d\n", x);
return 0;
}
Output
x = 11
- Explanation:
- The expression 5 + 2 * 3 is evaluated as 5 + (2 * 3) because * has higher precedence than +.
- (2 * 3) = 6, so the result is 5 + 6 = 11.
2. Associativity
#include <stdio.h>
int main() {
int x = 10;
int y = 5;
int z = 3;
x = y = z; // Assignment has right-to-left associativity.
printf("x = %d, y = %d\n", x, y);
return 0;
}
Output
x = 3, y=3
- Explanation:
- The expression x = y = z is evaluated as x = (y = z) due to the right-to-left associativity of = .
- y = z assigns the value 3 to y, so y = 3.
- x = y then assigns the value of y (which is 3) to x, so x = 3.
3. Combining Precedence and Associativity
#include <stdio.h>
int main() {
int x = 5, y = 10, z = 15;
int result = x + y * z / 5; // * and / have higher precedence than +.
printf("result = %d\n", result);
return 0;
}
Output
result = 35
- Explanation:
- * and / have the same precedence and are evaluated from left to right.
- First, y * z = 10 * 15 = 150.
- Then, 150 / 5 = 30.
- Finally, x + 30 = 5 + 30 = 35.