Precedence and Associativity Rules for Operators
Precedence and associativity rules are necessary for deterministic evaluation of expressions.
- The operators are shown with decreasing precedence from the top of the table.
- Operators within the same row have the same precedence.
- Parentheses, ( ), can be used to override precedence and associativity.
- The unary operators, which require one operand, include the postfix increment (++) and decrement (--) operators from the first row, all the prefix operators (+, -, ++, --, ~, !) in the second row, and the prefix operators (object creation operator new, cast operator (type)) in the third row.
- The conditional operator (? :) is ternary, that is, requires three operands.
- All operators not listed above as unary or ternary, are binary, that is, require two operands.
- All binary operators, except for the relational and assignment operators, associate from left to right. The relational operators are nonassociative.
- Except for unary postfix increment and decrement operators, all unary operators, all assignment operators, and the ternary conditional operator associate from right to left.
Precedence rules are used to determine which operator should be applied first if there are two operators with different precedence, and these follow each other in the expression. In such a case, the operator with the highest precedence is applied first.
2 + 3 * 4 is evaluated as 2 + (3 * 4) (with the result 14) since * has higher precedence than +.
Associativity rules are used to determine which operator should be applied first if there are two operators with the same precedence, and these follow each other in the expression.
Left associativity implies grouping from left to right, Right associativity implies grouping from right to left.
