Precedence of operators in C++ | Associativity of operators in C++
i. Precedence of operators in C++
Precedence is the priority given to each operator. Multiple operator in an expression get evaluated depending upon their precedence i.e. operator having higher precedence gets evaluated first followed by operators with lower precedence.
Example:
While calculating expression 10-3*4.
Multiplication operator (*) has better priority than subtraction operator (-), so 3*4 is solved first, then result of 3*4 =12 is subtracted from 10 The output of expression is -2.
Square Brackets and parenthesis have the highest priority and comma operator has the lowest priority.
Associativity of operators in C++
Associativity specifies the order to evaluate operators in an expression. if more than one operator of same precedence appear in an expression.
It can be either “Left to Right” or “Right to Left”.
Precedence and Associativity table in C++
lEVEL | OPERATORS | ASSOCIATIVITY |
1 | (), [] | Left to Right |
2 | Unary Operators (Logical NOT (!), ~, ++, –, +, -, *, &, (type), sizeof() ) | Right to Left |
3 | Arithmetic operators (*, /, %) | Left to Right |
4 | Arithmetic operators (+ , – ) | Left to Right |
5 | LEFT SHIFT & RIGHT SHIFT (<< , >>) | Left to Right |
6 | RELATIONAL OPERATORS (<, <= , > , >=) | Left to Right |
7 | RELATIONAL OPERATORS (= =, != ) | Left to Right |
8 | Bitwise and (&) | Left to Right |
9 | Bitwise and (^) | Left to Right |
10 | Bitwise or( | ) | Left to Right |
11 | LOGICAL and (&&) | Left to Right |
12 | LOGICAL OR (||) | Left to Right |
13 | CONDITIONAL OPERATOR (?:) | Right to Left |
14 | ASSIGNMENT OPERATORS (=, +=, -=, /=, *=, ^=, !=, <<=, >>= ) | Left to Right |
15 | COMMA OPERATOR(,) | Left to Right |