Associativity of Operators in C language

When an expression contains two operators with equal priority, the connection between them is established using the operators’ association.

The associativity can be of two types – from left to right or from right to left. Left associative right means that the left operand must be unambiguous. Without ambiguity in what sense? It should not be involved in the evaluation of any other sub-expressions. Similarly, in the case of association the Right to the Left must be the right operand unambiguous. Let us understand this with an example.

Consider the expression

a = 3 / 2 * 5  ;

Here there is a connection between the operators with the same priority, that is between / and *. This link is settled using the / and associative *. But both enjoy the association Left to Right. Figure shows for each operator which is the unambiguous operation and which is not.

Since both / and * have associative L with R and only / has the left operand unambiguously (a necessary condition for associating L with R), it is performed earlier.

Consider another expression

a = b = 3 ; 

Here both assignment operators have the same priority and the same association (from right to left). Figure shows for each operator which operand is unambiguous and which does not.

Because both = have associativity R to L and only the second = has operating as unequivocal (necessary condition for R to L associativity) the second = is carried out earlier.


Consider another expression

z = a * b + c / d ; 

Here * and / enjoy the same priority and the same associativity (from left to right). Figure shows for each operator who is the operator unambiguous and which is not.

Here, because the operands remaining for both operators are unambiguous, the compiler is free to perform

c language topics

V.L.S.I Topics

Related Tech-News

Leave a Comment