Hierarchy of operators in C

Hierarchy of Operators

While executing an arithmetic statement, which has two or more operators, we may confuse to calculate the result. For example, the expression 2 * x – 3 * y corresponds to (2x) – (3y) or to 2(x-3y)? Similarly, A / B * C correspond to A / (B * C) or to (A / B) * C?

To answer these questions, one has to understand the ‘hierarchy’ of operations. The priority in which the operations in an arithmetic statement are performed is called the hierarchy of operations.

Precedence is also known as priority.

Associativity: associativity is the direction in which the compiler evaluates the expression.

Associativity of Operators

When an expression contains two operators of equal priority the tie between them is settled using the associativity of the operators. Associativity can be of two types—Left to Right or Right to Left. Left to Right associativity means that the left operand must be unambiguous. Unambiguous in what sense? It must not be involved in evaluation of any other sub-expression. Similarly, in case of Right to Left associativity the right operand must be unambiguous. Let us understand this with an example.

Operators having equal precedence (or priority) are evaluated using associativity.

Consider the expression

a = 3 / 2 * 5;

Here there is a tie between operators of same priority, that is between / and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity. Figure 1.10 shows for each operator which operand is unambiguous and which is not.

Operator Left Right Remark
/ 3 2 or 2*5 Left operand is unambiguous. Right is not.
* 3/2 or 2 5 Right operand is unambiguous. Left is not.
heirarchy_of_operators

Note that 6 / 4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore would evaluate to only an integer constant. Similarly, 5 / 8 evaluates to zero, since 5 and 8 are integer constants and hence must return an integer value.

operator_heirarchy


precedence_table
precedence_table

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »