Operator precedence in C
Operator precedence in C
In addition to operator precedence, C also has rules for operator associativity, which
determine the order in which operators of the same precedence are evaluated. For example,
the addition and subtraction operators have the same precedence, but they are left-associative,
which means that they are evaluated from left to right. So the expression "2 + 3 - 4" is
evaluated as "(2 + 3) - 4", which is equal to 1.
It's important to understand operator precedence and associativity in C, as they can affect the
outcome of an expression and lead to unexpected results if not used correctly. By
understanding these rules, you can write more efficient and correct code.
Operators in C have associativity, which defines the order in which operators with the same
precedence are evaluated. There are two kinds of associativity: left-to-right and right-to-left.
Note that operators with left-to-right associativity are evaluated from left to right, while
operators with right-to-left associativity are evaluated from right to left. This can affect the
order of operations when multiple operators of the same precedence are used in an
expression.
C Program:
1. #include <stdio.h>
2.
3. int main() {
4. int x = 2, y = 3, z = 4;
5. int result = x + y * z; // result = 14
6. printf("Result: %d\n", result);
7.
8. int a = 5, b = 6, c = 7;
9. int result2 = (a + b) * c; // result2 = 77
10. printf("Result2: %d\n", result2);
11.
12. int d = 8, e = 9, f = 10;
13. int result3 = d + e % f; // result3 = 17
14. printf("Result3: %d\n", result3);
15.
16. int g = 11, h = 12, i = 13;
17. int result4 = g * h / i; // result4 = 10
18. printf("Result4: %d\n", result4);
19.
20. int j = 14, k = 15, l = 16;
21. int result5 = j == k || l > k; // result5 = 1 (true)
22. printf("Result5: %d\n", result5);
23.
24. return 0;
25. }
OutputResult: 14 Result2: 77 Result3: 17 Result4: 10 Result5: 1
Types of Expressions:
Expressions may be of the following types:
#include <stdio.h>
void main()
int a=2,b=3,c=4,z;
z=a+b-(a*c);
printf("Result= %d",z);