C Operator Precedence
In this page:
What is Precedence?
Operator precedence is the fixed order C uses to decide which operator in a mixed expression gets evaluated first, following the same logic as algebra's "multiply before you add" rule you'd apply by hand.
Example: What is Precedence?
#include <stdio.h>
int main() {
int result = 2 + 3 * 4;
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Operator Associativity
When two operators in the same expression share equal precedence, associativity decides the tie: most C operators associate left-to-right, but a few (like assignment) associate right-to-left instead.
Example: Operator Associativity
#include <stdio.h>
int main() {
int x, y;
x = y = 10;
printf("%d %d", x, y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Arithmetic Hierarchy
*, /, and % all share the same precedence level and are evaluated before + and -, so 2 + 3 * 4 evaluates the multiplication first, giving 14 rather than 20.
Example: Arithmetic Hierarchy
#include <stdio.h>
int main() {
int result = 2 + 3 * 4;
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Parentheses
Parentheses always take priority over C's default precedence rules, so wrapping part of an expression in () forces it to be evaluated first -- the clearest way to make your intended order of operations explicit rather than relying on memorized rules.
Example: Using Parentheses
#include <stdio.h>
int main() {
int result = (2 + 3) * 4;
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Relational and Logical Priority
Arithmetic operators bind tighter than relational operators, which in turn bind tighter than logical operators, so a + b > c && d evaluates the addition, then the comparison, then the logical AND, in that order.
Example: Relational and Logical Priority
#include <stdio.h>
int main() {
int a = 2, b = 3, c = 4, d = 1;
int result = a + b > c && d;
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: