Lesson 43 +10 XP

Operator Precedence

C++ Operator Precedence

When several operators share one expression, C++ needs a rule for which one runs first. That rule is precedence: some operators "bind tighter" than others.

Multiplication before addition

cout << (2 + 3 * 4) << endl;    // 14, not 20
cout << ((2 + 3) * 4) << endl;  // 20

In 2 + 3 4, the runs first (12), then the addition (14). This mostly follows school math rules.

The usual order

From highest to lowest for the operators in this course:

  • *, /, %
  • +, -
  • ==, !=, >, <, >=, <=
  • &&, then ||

Parentheses always win

If you ever feel unsure, put parentheses where you want. They override any default precedence, and they make the code obvious.

cout << ((2 + 3) * 4) << endl;  // crystal clear: 20

Associativity: same power, left to right

For operators with equal precedence, like a - b - c, C++ evaluates left to right: (a - b) - c.

TL;DR

  • Precedence decides which operator runs first.
  • *, /, % come before +, -.
  • Comparisons come after those.
  • Parentheses override everything; use them when unsure.