Associativity of Operators

When an expression contains two or more operators of the equal priority then their order of execution is decided by using the associativity of the operators. 

Associativity of the operators can be of two types - Left to Right and Right to Left. 

Left to Right - Left operand must be unambiguous (must not involeve in any other sub-expression)

Right to Left - Right operand must be unambiguous 

Example -   Consider the following expression - 

a = 3 / 2 * 5 ; 

Here both / and * have the same priority. In this case order of evaluation will be decided by using the associativity of operators. Both have the L-R associativity. That means Left operand must be unambiguous. 

for division operator ( / ) left operand is 3 which is unambiguous and for multiplication ( * ) operator left operand is 3 / 2 which is ambiguous. 

Therefore division will be performed first. 


Example -2 Consider the following expression in C 

a = b = 3 ; 

Here both assignment operators have the same priority therefore their order of evaluation will be decided by the associativity of the operators. 

Assignment operator has R-L associativity that means the right operand should be unambiguous. 

a = b ;  (right operand is ambiguous)  

b = 3 ;  (right operand is unambiguous) it will be executed first. 


Last modified: Wednesday, 17 November 2021, 4:26 PM