Understanding Operator Precedence and Associativity in C
This article is a complementary resource to the Learn C Programming course
This article is a complementary resource to the Learn C Programming course
Understanding Operator Precedence and Associativity in C
In C, operator precedence and associativity determine the order in which operations are performed in an expression.
Consider the following program:
#include <stdio.h>
int main() {
int result = 10 - 5 + 3 * 2;
printf("%d", result);
return 0;
}
Here is how the value of the result variable is calculated:
10 - 5 + 3 * 2
= 10 - 5 + 6
= 11
Here, the order of operations is:
The rules C follows to evaluate any expression are provided by operator precedence and associativity.
Here's an overview of operator precedence in JavaScript (from highest to lowest):
| Operator | Description | Precedence |
|---|---|---|
() |
Parentheses | Highest |
*, /, % |
Multiplication, Division, Modulo | High |
+, - |
Addition, Subtraction | Medium |
<, >, <=, >= |
Comparisons | Low |
==, !=, ===, !== |
Equality/Inequality | Lowest |
Associativity determines how operators of the same precedence are evaluated.
JavaScript follows two types of associativity:
+, -, *, and /, are evaluated from left to right.=) evaluate from right to left.Consider the following expression:
int result = 20 - 5 - 3;
printf("%d", result); // Output: 12
Here, subtraction is evaluated left to right: (20 - 5) - 3 = 12.
Now, let's look at another example:
int result = 10 / 2 * 3;
printf("%d", result); // Output: 15
In this case, both multiplication (*) and division (/) share the same precedence and are evaluated from left to right. So, the division is performed first:
(10 / 2) * 3 = 15
The assignment operator is right-to-left associative. Let's see an example,
int a = b = c = 10;
printf("%d %d %d", result); // Output: 10 10 10
This is evaluated as a = (b = (c = 10)).
Without understanding precedence, it's easy to make mistakes. For example:
int result = 12 / 2 / 2;
printf("%d", result); // Output: 3
You might expect 12, but C evaluates it as (12 / 2) / 2 = 6 / 2 = 3.
To avoid such errors, always use parentheses to clarify your intentions.
int result = 12 / (2 / 2);
printf("%d", result); // Output: 12
To avoid confusion and ensure clarity, always use parentheses to explicitly define the order of operations in complex expressions. For example:
int result = 30 / (2 * 3)
printf("%d", result); // Output: 5
Here, parentheses ensure that 2 * 3 is evaluated first, changing the result of the division. Without parentheses, the division would be performed first, leading to a different result.
Using parentheses clarifies your intentions, eliminates ambiguity, and helps prevent logic errors.