In the following table, the operators are shown top-to-bottom in decreasing order of precedence.
Category | Operators |
Parenthesis | () |
Unary | ! ++ -- + (unary plus) - (unary minus) (type) (cast operator) |
Multiplicative | * / % |
Additive | + (addition) - (subtraction) |
Relational and equality | < > <= >= == != |
Logical AND | && |
Logical OR | || |
Conditional | ?: |
Assignment | = += -= *= /= %= |
In the above table, the operators within the same category have equal precedence.
The unary (except ++ and --), conditional and assignment operators are right associative. This means that for these categories, operators with equal precedence will be evaluated from the right to the left.
The other categories of operators (except ++ and --) are left associative. This means that for these categories, operators with equal precedence will be evaluated from the left to the right.
See the following program for an example:
#include <iostream.h> main() { float a = 1.1, b = 1.2, c = 1.3, d = 1.4, e = 0, x = 2, y; x += y = 4.7 + (a == b && c < d ? 3.2 : 1.4) - 7 * - ! e++; // e = 1, x = 15.1, y = 13.1 cout << "e=" << e << ", x=" << x << ", y=" << y << endl; return 0; } |
The following shows how the statement in red above is executed:
|
x += | y = |
4.7 + |
( |
a == b |
&& |
c < d |
? 3.2 : 1.4) |
- |
7 * |
- |
! |
e++ |
(1) |
x += | y = |
4.7 + |
( |
a == b |
&& |
1.3 < 1.4 |
? 3.2 : 1.4) |
- |
7 * |
- |
! |
e++ |
(2) |
x += |
y = |
4.7 + |
( |
1.1 == 1.2 |
&& |
1 |
? 3.2 : 1.4) |
- |
7 * |
- |
! |
e++ |
(3) |
x += |
y = |
4.7 + |
( |
0 |
&& |
1 |
? 3.2 : 1.4) |
- |
7 * |
- |
! |
e++ |
(4) |
x += | y = |
4.7 + |
( |
0 |
? 3.2 : 1.4) |
- |
7 * |
- |
! |
e++ |
||
(5) |
x += | y = |
4.7 + |
1.4 |
- |
7 * |
- |
! |
e++ |
||||
(6) |
x += |
y = |
4.7 + |
1.4 |
- |
7 * |
- |
! |
0 |
||||
(7) |
x += |
y = |
4.7 + |
1.4 |
- |
7 * |
- |
1 |
|||||
(8) |
x += |
y = |
4.7 + |
1.4 |
- |
7 * |
(-1) |
||||||
(9) |
x += |
y = |
4.7 + |
1.4 |
- |
(-7) |
|||||||
(10) |
x += |
y = |
6.1 |
- |
(-7) |
||||||||
(11) |
x += |
y = |
13.1 |
||||||||||
(12) |
x += |
13.1 |
|||||||||||
(13) |
15.1 |
In particular: