Skip to main content

Precedence and associativity

Short answer

Precedence dictates which operator evaluates first when types differ (e.g., * before +). Associativity resolves order for same‑precedence operators (left‑to‑right for +, -, *, /; right‑to‑left for =). Example: a+b*c multiplies first; a-b-c left‑to‑right; x=y=z assigns right‑to‑left.

Explain with an example the role that precedence and associativity of an operator play in the execution of an expression.

Precedence decides which operator is evaluated first when an expression has different operators. Associativity decides the order (left to right or right to left) when operators of the same precedence appear together.

  • Precedence: *, /, % are higher than +, -.
  • Associativity: + - * / are left to right; assignment = and unary operators are right to left.
  • Brackets ( ) override both.

Example, with a = 10, b = 5, c = 2:

r1 = a + b * c;   /* * first: 10 + 10 = 20 */
r2 = (a + b) * c; /* brackets first: 15 * 2 = 30 */
r3 = a - b - c;   /* left to right: (10-5)-2 = 3 */
x = y = z = 7;    /* right to left: z=7, then y=z, then x=y */

Printing r1, r2, r3, x, y and z gives 20 30 3 7 7 7.

So precedence gives the correct result of mixed expressions without brackets, and associativity removes ambiguity in chains of equal-level operators. Without them, the same expression could give different values.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 3 questions →