Operator precedence determines the order in which operators are grouped when an expression contains multiple operators. Operators with higher precedence are grouped before operators with lower precedence.
#include <stdio.h>
int main()
{
int result;
result = 10 + 5 * 2;
printf("result = %d\n", result);
return 0;
}
Example Output #
result = 20
Explanation #
The expression:
10 + 5 * 2
contains + and *. Multiplication has higher precedence than addition, so it is grouped first:
10 + (5 * 2)
The result is therefore 20.
Parentheses have higher precedence than the operators inside the expression and can be used to explicitly change the grouping:
result = (10 + 5) * 2;
This produces 30.
Operator Precedence Table #
The following table lists the commonly used C operators from higher precedence to lower precedence.
| Precedence | Operators | Description | Associativity |
|---|---|---|---|
| 1 | () [] . -> |
Function call, array subscript, member access | Left-to-right |
| 2 | ++ -- + - ! ~ sizeof (type) |
Unary operators, sizeof, cast |
Right-to-left |
| 3 | * / % |
Multiplication, division, remainder | Left-to-right |
| 4 | + - |
Addition, subtraction | Left-to-right |
| 5 | << >> |
Bitwise shifts | 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 | ?: |
Conditional operator | Right-to-left |
| 14 | = += -= *= /= %= <<= >>= &= ^= |= |
Assignment operators | Right-to-left |
| 15 | , |
Comma operator | Left-to-right |
Precedence determines grouping; associativity determines grouping when operators have the same precedence.