3.5 — Which goes first? (precedence)
Read one box at a time. No rush.
Order matters#
When an expression has many operators, C++ follows rules to decide which goes first. This is called precedence.
A simplified order (top goes first):
| Goes first | Operators |
|---|---|
| 1 | ( ) brackets |
| 2 | ! ++ -- -x |
| 3 | * / % |
| 4 | + - |
| 5 | < <= > >= |
| 6 | == != |
| 7 | && |
| 8 | || |
| 9 | = += -= and friends |
C++
int x { 2 + 3 * 4 }; // 14, because * goes before +When in doubt, use brackets#
C++
bool ok { (age > 12 && age < 20) || isVip };Brackets make the order obvious, even if you don't remember the table.
Good habit
You do not need to memorise this table. Use ( ) whenever the order is not obvious. It helps people reading your code too.
Tip: press ← / → to move between lessons, / to search.