Operator Precedence and Associativity
Operator Precedence
Definition: Precedence defines the priority of operators in expressions. Operators with higher precedence are evaluated before those with lower precedence.
int result = 2 + 3 * 4; // result = 14
In this case, the multiplication (*) has higher precedence than addition (+), so 3 * 4 is evaluated first, followed by 2 + 12.
Associativity
- Definition: Associativity defines the direction in which operators of the same precedence are evaluated (left-to-right or right-to-left).
- Left-to-Right Associativity: Operators are evaluated from left to right.
- Right-to-Left Associativity: Operators are evaluated from right to left.
int a = 10, b = 5, c = 3;
int result = a - b - c; // result = (a - b) - c = (10 - 5) - 3 = 2
Subtraction has left-to-right associativity, so a - b is evaluated first.
Operator Precedence and Associativity Table
Below is a table of operators arranged by precedence from highest to lowest. Operators with the same precedence are grouped, and the associativity indicates the direction in which expressions are evaluated.
| Precedence | Operator | Associativity | Category |
|---|---|---|---|
| 1 (Highest) | ()[]->. | Left-to-Right | Function call, array, member access |
++-- (postfix) | Left-to-Right | Post-increment, post-decrement | |
| 2 | ++-- (prefix) +-!~ | Right-to-Left | Unary increment, decrement, logical NOT, bitwise NOT, unary plus and minus |
* (dereference) & (address-of) | Right-to-Left | Pointer dereference, address-of | |
(type) (cast) sizeof | Right-to-Left | Type cast, size of | |
newdelete | Right-to-Left | Dynamic memory allocation | |
| 3 | */% | Left-to-Right | Multiplication, division, modulus |
| 4 | +- | Left-to-Right | Addition, subtraction |
| 5 | <<>> | Left-to-Right | Bitwise left shift, right shift |
| 6 | <<=>>= | Left-to-Right | Relational less than, greater than |
| 7 | ==!= | Left-to-Right | Equality, inequality |
| 8 | & | Left-to-Right | Bitwise AND |
| 9 | ^ | Left-to-Right | Bitwise XOR |
| 10 | | | Left-to-Right | Bitwise OR |
| 11 | && | Left-to-Right | Logical AND |
| 12 | || | Left-to-Right | Logical OR |
| 13 | ?: | Right-to-Left | Ternary conditional |
| 14 | =+=-=*=/=%=<<=>>=&=^=|= | Right-to-Left | Assignment and compound assignment |
| 15 (Lowest) | , | Left-to-Right | Comma operator |
Leave a comment
Your email address will not be published. Required fields are marked *


