Operator precedence and associativity show the order or sequence in which operators are used. For example, you have below expression of operators:
4 + 3 * 5 > 4 * (3 + 1) – 5
Find its value? Find its execution sequence or order of the operators?
According to math laws, parentheses expression is evaluated or executed first. (Nested parentheses can be used, in this situation inner parentheses expression execute first). When an expression used without parentheses, then the precedence rules and the associativity rules are applied according to the operator’s order.
Precedence
In operators, precedence rule defines which operator will use first and which operator will use second and go next until operators’ expression will end. Operators are listed below in decreasing order of precedence. The below table (zitoc – 1.0) shows that the operators you have learned about.
Associativity
When some operators have the same precedence are next to each other, their associativity shows the sequence of evaluation. All binary operators are left-associative except single one assignment operators. For example, the operator (+) and operator (-) are the same precedence and are left-associative.
Below both expression are same.
w – x + y – z
((w – x) + y) – z
Precedence
Operator
12
var– and var++ (Postfix)
11
–, + (Unary minus and plus), –var and ++var (Prefix)
10
(type) (Casting)
9
! (Not)
8
/, %, * (Division, remainder and multiplication)
7
–, + (Binary subtraction and addition)
6
<,>,<=,>= (Comparison)
5
!=, == (Equality)
4
^ (Exclusive OR)
3
&& (AND)
2
|| (OR)
1
=, -=, +=, %=, *=, /= (Assignment operator)
Table: (zitoc – 1.0) | Operator Precedence Chart
Note: Assignment operators are right associative.
Operators are listed below in decreasing order of precedence from the top level to bottom level. Operators have the same precedence which has the same group, and their associativity also showed in the table.