Expressions and Precedence
Expressions combine operands and operators, while precedence and associativity decide how the language groups them.
Grouping controls expression meaning.
Languages must decide how to parse and evaluate dense expressions like a + b * c or a - b - c. Precedence ranks operators. Associativity breaks ties between operators at the same level.
When to reach for this
Reach for this concept whenever an expression mixes several operators or whenever you are designing a parser, reading dense code, or deciding whether parentheses are necessary.
Why this matters
Without explicit rules, expressions become ambiguous. Those rules shape both the parse tree and the meaning of the program.
The mental model
Precedence sets priority
Multiplication usually groups before addition, so a + b * c becomes a + (b * c) unless parentheses say otherwise.
Association breaks ties
For operators with the same precedence, the language decides whether grouping happens left to right or right to left.
Step through the concept
How to use this page
Follow the animation one state at a time and connect the code to the runtime behavior.
- Watch multiplication group before addition.
- Compare equal-precedence subtraction operators.
- See parentheses override default grouping.
Operator Precedence
Multiply before adding.
2 + 3 * 4Read Tokens
The expression contains addition and multiplication.
Evaluation Order
Pending
Three grouping rules
| Aspect | Rule | Effect |
|---|---|---|
| Precedence | Ranks operators | Higher rank groups first |
| Association | Breaks equal-rank ties | Chooses left or right |
| Parentheses | Creates explicit groups | Overrides default rules |
The short version
- Precedence answers which operator groups first.
- Associativity answers how equal-precedence operators group.
- Parentheses override both and improve readability when the expression is not obvious.
- These rules affect meaning, not just style.