What are Precedence and Associativity?
Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.
For example:
1 | x = 10 + 5 * 2; |
In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2) and then multiplied value is added to 10.
In the following table, the precedence of an operator decreases from top to down:
Category | Operator | Associativity |
---|---|---|
Postfix | >() [] . (dot operator) | Left to right |
Unary | >++ – – ! ~ | Right to left |
Additive | >+ – | Left to right |
Relational | >> >= < <= | Left to right |
Equality | >== != | Left to right |
Bitwise AND | >& | Left to right |
Bitwise OR | >| | Left to right |
Bitwise XOR | >^ | Left to right |
Logical AND | >&& | Left to right |
Logical OR | >|| | Left to right |
Conditional | ?: | Right to left |
Assignment | >= += -= *= /= %= >>= <<= &= ^= |= | Right to left |