Operator Precedence and Associativity
You'll learn how programming languages decide which operations to perform first in complex expressions, and how to control that order.
What's the Problem?
When you write an expression like 5 + 3 * 2, does the computer add first (getting 8 * 2 = 16) or multiply first (getting 5 + 6 = 11)? Just like in mathematics, programming languages follow strict rules to avoid confusion.
Operator Precedence
Precedence determines which operators are evaluated first when multiple operators appear in the same expression. Higher precedence operators "bind tighter" and execute before lower precedence ones.
In most programming languages (like math):
- Multiplication and division have higher precedence than addition and subtraction
- So
5 + 3 * 2evaluates as5 + (3 * 2) = 11
Think of precedence like urgency levels: multiplication is "urgent" and gets handled before the "less urgent" addition.
Associativity
Associativity determines the order when operators have the same precedence. Most arithmetic operators are left-associative, meaning they evaluate from left to right.
10 - 5 - 2evaluates as(10 - 5) - 2 = 3, not10 - (5 - 2) = 720 / 4 / 2evaluates as(20 / 4) / 2 = 2.5, not20 / (4 / 2) = 10
Using Parentheses for Control
You can always override precedence and associativity with parentheses (). They have the highest precedence of all.
(5 + 3) * 2 = 16forces addition first10 - (5 - 2) = 7changes the associativity
Key Takeaway: Operator precedence determines which operations execute first in an expression, associativity handles same-precedence operators (usually left-to-right), and parentheses let you override both for explicit control.