Precedence of operators
In C, operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. Here’s a list of operators in C, organized by their precedence from highest to lowest:
1. Postfix Operators
expr++
(Post-increment)expr--
(Post-decrement)
2. Unary Operators
++expr
(Pre-increment)--expr
(Pre-decrement)+
(Unary plus)-
(Unary minus)!
(Logical NOT)~
(Bitwise NOT)&
(Address of)*
(Dereference)
3. Multiplicative Operators
*
(Multiplication)/
(Division)%
(Modulus)
4. Additive Operators
+
(Addition)-
(Subtraction)
5. Shift Operators
<<
(Left shift)>>
(Right shift)
6. Relational Operators
<
(Less than)<=
(Less than or equal to)>
(Greater than)>=
(Greater than or equal to)
7. Equality Operators
==
(Equal to)!=
(Not equal to)
8. Bitwise AND Operator
&
(Bitwise AND)
9. Bitwise XOR Operator
^
(Bitwise XOR)
10. Bitwise OR Operator
|
(Bitwise OR)
11. Logical AND Operator
&&
(Logical AND)
12. Logical OR Operator
||
(Logical OR)
13. Conditional (Ternary) Operator
? :
(Ternary)
14. Assignment Operators
=
(Simple assignment)+=
,-=
,*=
,/=
,%=
,&=
,|=
,^=
,<<=
,>>=
(Compound assignments)
15. Comma Operator
,
(Comma)
Example to Demonstrate Precedence
Here’s a small example illustrating operator precedence:
#include <stdio.h>
int main() {
int a = 5, b = 10, c;
// Example of precedence
c = a + b * 2; // b * 2 is evaluated first
printf(“Result: %d\n”, c); // Output: 25 (5 + 20)
c = (a + b) * 2; // Parentheses change precedence
printf(“Result: %d\n”, c); // Output: 30 (15 * 2)
c = a < b && a > 0; // Both comparisons are evaluated
printf(“Result: %d\n”, c); // Output: 1 (true)
return 0;
}
- Parentheses: You can change the order of evaluation by using parentheses. They have the highest precedence.
- Associativity: Operators with the same precedence are evaluated based on their associativity, which can be left-to-right or right-to-left. For instance, assignment operators are right-to-left, while most arithmetic and relational operators are left-to-right.