Operator Precedence and Associativity in C
Operator Precedence and Associativity in C
Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)
1. Operator Precedence in C
Operator precedence determines which operation is performed first when there are multiple
operators in an expression. Operators with higher precedence are evaluated before those
with lower precedence.
int x = 15 + 20 * 3;
// '*' has higher precedence than '+', so evaluated as: 15 + (20 * 3) = 75
2. Operator Associativity
Types of Associativity
1. Left-to-Right Associativity: Operators at the same level are evaluated from left to right.
2. Right-to-Left Associativity: Operators at the same level are evaluated from right to left.
int result = 10 - 4 - 2;
// Evaluated as: (10 - 4) - 2 = 4
int a = 10;
int b = 20;
int c = 30;
a = b = c; // Right-to-left: a = (b = c) → b gets 30, then a gets 30
int main() {
int a = 5, b = 10, c = 2, result;
// Evaluate
int a = 5, b = 10, c = 2, result;
result = 14 && 1 || a == c
result = 1 || a == c
Equality Operator (a == c)
a == c → 5 == 2 → 0 (false)
result = 1 || 0
5. Summary
Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)
#include <stdio.h>
int main() {
int result;
return 0;
}
Parentheses can override precedence to ensure correct evaluation order.
Step-by-Step Calculation:
✅ Final Output:
Result: 7