Learn C++ operator precedence with clear examples and simple explanations. Understand how arithmetic, relational, logical, assignment, unary, and increment/decrement operators are evaluated in C++ programs.
Operator precedence tells C++ which operator should be performed first when an expression contains more than one operator.
int result = 5 + 3 * 2;
Multiplication * has higher precedence than addition +.
So:
5 + (3 * 2)
= 5 + 6
= 11
Answer: 11
Remember:
Higher precedence → performed first
For example:
10 - 4 / 2
/ has higher precedence than -.
10 - (4 / 2)
= 10 - 2
= 8
For beginners, remember this order:
| Priority | Operators | Meaning | ||
|---|---|---|---|---|
| 1 | () |
Parentheses | ||
| 2 | ++ -- |
Increment / Decrement | ||
| 3 | * / % |
Multiplication, Division, Modulus | ||
| 4 | + - |
Addition, Subtraction | ||
| 5 | < <= > >= |
Relational | ||
| 6 | == != |
Equality | ||
| 7 | && |
Logical AND | ||
| 8 | ` | ` | Logical OR | |
| 9 | = += -= *= /= |
Assignment |
()
↓
++ --
↓
* / %
↓
+ -
↓
< <= > >=
↓
== !=
↓
&&
↓
||
↓
=
Use parentheses () when you want something to be calculated first.
int result = (5 + 3) * 2;
First:
5 + 3 = 8
Then:
8 * 2 = 16
Answer: 16
Compare:
int result = 5 + 3 * 2;
Answer:
11
But:
int result = (5 + 3) * 2;
Answer:
16
*, /, and %These operators have the same precedence.
int x = 20 / 5 * 2;
When operators have the same precedence, C++ generally evaluates them from left to right.
20 / 5 = 4
4 * 2 = 8
Answer: 8
int x = 17 % 5 + 2;
First %:
17 % 5 = 2
Then:
2 + 2 = 4
Answer: 4
+ and -+ and - have the same precedence and are evaluated from left to right.
int x = 10 - 3 + 2;
First:
10 - 3 = 7
Then:
7 + 2 = 9
Answer: 9
Consider:
int result = 5 + 2 * 3;
*2 * 3 = 6
+5 + 6 = 11
Therefore:
result = 11
int result = (5 + 2) * 3;
5 + 2 = 7
7 * 3 = 21
Therefore:
result = 21
When two operators have the same precedence, they are generally evaluated from left to right.
Example:
int result = 20 / 5 * 2;
20 / 5 = 4
4 * 2 = 8
So:
Answer = 8
Not:
20 / (5 * 2) = 2
When an expression becomes difficult to understand, use parentheses.
Instead of:
int result = a + b * c - d / e;
Think of it as:
int result = a + (b * c) - (d / e);
Parentheses make the order clear and reduce mistakes.
Parentheses → Increment/Decrement → Multiply/Divide/Modulus → Add/Subtract → Relational → Equality → AND → OR → Assignment
()
++ --
* / %
+ -
< <= > >=
== !=
&&
||
=
First check parentheses, then higher-precedence operators, and when operators have equal precedence, follow their associativity (commonly left-to-right for arithmetic operators).