Introduction to C Programming
Operators in C Part 1
Operators in C Part 2
Precedence and Associativity Of Operators in C
If else Statements in C
Switch Statement in C
Loops in C
While and Do-While loops in C
Nested loops in C
Loop Control Statements in C
1D Arrays in C
2D Arrays in C
Pattern Printing in 2D arrays
Functions in C
Pointers in C
ASCII Encoding and Typecasting in C
Precedence and Associativity of Operators
When multiple operators are used in one expression such as ++,-- or + or *, etc
we need to decide the order in which to evaluate different operators on the basis of
priority in order to get the correct results. This is called precedence of operators.
Associativity means that when there are multiple operators of the same kind for e.g - a*b*c or a+b+c etc. then the direction in which to evaluate the expression - left to right or right to left.
Associativity means that when there are multiple operators of the same kind for e.g - a*b*c or a+b+c etc. then the direction in which to evaluate the expression - left to right or right to left.
- C operator Precedence and Associativity Table
- Example
Jump to specific sections
C Operator Precedence and Associativity Table
| Operator | Associativity | Precedence |
|---|---|---|
| () [] -> . | Left to right | Highest |
| ++ -- + - ! ~ (type) * & sizeof | Right to left | |
| * / % | Left to right | |
| + - | Left to right | |
| << >> | Left to right | |
| < <= > >= | Left to right | |
| == != | Left to right | |
| & | Left to right | |
| ^ | Left to right | |
| | | Left to right | |
| && | Left to right | |
| || | Left to right | |
| ?: | Right to left | |
| = += -= *= /= %= <<= >>= &= ^= |= | Right to left | |
| , | Left to Right | Lowest |
Example
#include<stdio.h>
void main()
{
int a=19,b=10,c=40,d=20,e=2;
// This expression will be evaluated as (a + (b * (c/d) ) ) based on precedence of operators.
printf("Value of a+b*c/d = %d \n",a+b*c/d);
// Brackets have the highest priority, this expression will be evaluated as
//(((++a) + ((b*c)/(d--)))+(--e) )
printf("Value of (++a+(b*c)/d--)+--e = %d \n",(++a+(b*c)/d--)+--e);
}
Output
Value of a+b*c/d = 39
Value of (++a+(b*c)/d--)+--e = 41