Left-to-right associativity
What you'll learn: How C decides the order of operations when multiple operators have the exact same level of importance.
The Tie-Breaker Rule
In previous lessons, we learned about precedence, which is like the "order of operations" in math (multiplication happens before addition). But what happens when you have a string of operators that are all equally important?
Imagine a row of people waiting for a bus. If everyone has the same priority, the bus driver simply starts with the person at the front of the line and moves backward. In C, this "first-come, first-served" logic is called Left-to-Right Associativity. When the compiler sees a line of equal-ranking operators, it processes them in the order they appear from left to right.
Multiplication and Division
Multiplication (*) and division (/) share the same precedence level. If you mix them in a single expression, C doesn't guess which is more important; it simply reads them like a sentence.
Consider the expression: 12 / 3 * 2
If you did the multiplication first, you’d get 12 / 6 = 2. But because of left-to-right associativity, C groups the leftmost operation first:
- First, it calculates
12 / 3, which is4. - Then, it takes that result and multiplies it:
4 * 2. - The final answer is
8.
Seeing it in Code
Most arithmetic operators in C—including addition, subtraction, multiplication, and division—follow this left-to-right rule. It ensures that your code is predictable and consistent.
#include <stdio.h>
int main() {
// Both / and * have the same precedence
// Step 1: 20 / 5 = 4
// Step 2: 4 * 2 = 8
int result1 = 20 / 5 * 2;
// Both - and + have the same precedence
// Step 1: 10 - 5 = 5
// Step 2: 5 + 3 = 8
int result2 = 10 - 5 + 3;
printf("Result 1: %d\n", result1);
printf("Result 2: %d\n", result2);
return 0;
}
Why It Matters
Without this rule, code would be chaotic. Associativity provides a "tie-breaker" that keeps calculations stable. While you can always use parentheses () to force a different order, understanding left-to-right associativity helps you read code more naturally, just like reading a book.
Key takeaway
When operators have equal precedence, C evaluates them from left to right.