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.
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.
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
var– and var++ (Postfix)
–, + (Unary minus and plus), –var and ++var (Prefix)
/, %, * (Division, remainder and multiplication)
–, + (Binary subtraction and addition)
!=, == (Equality)
^ (Exclusive OR)
=, -=, +=, %=, *=, /= (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.