Understanding Operator Precedence in C: Rules and Evaluation Order
Learn how operator precedence in C controls the order of operations in expressions. Discover which operators take priority and how precedence impacts the evaluation of complex expressions in your C programs.
Operator Precedence in C
In C, operator precedence determines the order of evaluation in expressions. Operators with higher precedence are evaluated before those with lower precedence.
Operator Precedence Table
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ -- | Left to right |
Unary | + - ! ~ ++ -- (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %= >>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Operator Associativity
Associativity determines the order of evaluation when two operators of the same precedence appear. For example:
Code
15 / 5 * 2
The division (/) and multiplication (*) operators have the same precedence and are evaluated left to right:
Output
(15 / 5) * 2 = 6
Example 1: Basic Operator Precedence
In this example, multiplication and division have higher precedence than addition:
Code
#include <stdio.h>
int main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e = a + b * c / d;
printf("e: %d\n", e);
return 0;
}
Output
e: 50
Example 2: Using Parentheses
Parentheses change the order of evaluation by giving their contents the highest precedence:
Code
#include <stdio.h>
int main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e = (a + b) * c / d;
printf("e: %d\n", e);
return 0;
}
Output
e: 90
Example 3: Multiple Parentheses
Parentheses can be used to group different parts of an expression:
Code
#include <stdio.h>
int main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e = (a + b) * (c / d);
printf("e: %d\n", e);
return 0;
}
Output
e: 90
Precedence of Increment/Decrement Operators
The ++
and --
operators can be used as prefix or postfix. Postfix increment/decrement has higher precedence than prefix:
Code
#include <stdio.h>
int main() {
int x = 5, y = 5, z;
z = x++;
printf("Postfix increment: x: %d z: %d\n", x, z);
z = ++y;
printf("Prefix increment: y: %d z: %d\n", y, z);
return 0;
}
Output
x: 6 z: 5
y: 6 z: 6
Logical operators &&
and ||
have left-to-right associativity. The second operand is evaluated only if necessary to determine the result:
For example, in x > 50 && y > 50
, y > 50
is evaluated only if x > 50
is true.