Course contentsShow
← Computer Science
Lesson 155 of 2,8724. Introduction to ProgrammingFree lesson

Operator Precedence and Associativity

Understanding the order in which operators are evaluated and how to use parentheses for control.

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 * 2 evaluates as 5 + (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 - 2 evaluates as (10 - 5) - 2 = 3, not 10 - (5 - 2) = 7
  • 20 / 4 / 2 evaluates as (20 / 4) / 2 = 2.5, not 20 / (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 = 16 forces addition first
  • 10 - (5 - 2) = 7 changes 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.