Programming

C – Precedence and Associativity and Rules

The compiler evaluates a single operator at a time. If more than one operator appears in an expression the compiler should decide which one to evaluate first.

The rule that specifies which operator to evaluate first called precedence of the operator.

The operator with higher precedence is evaluated first and lower precedence operators are evaluated next.

If in a line, same precedence operators appear, then the compiler uses left-to-right or right-to-left rule according to operator type.

The process of evaluating the same precedence operator from left to right or right to left is called associativity.

In left to right associativity, the operator at the left-most part is evaluated first and it moves towards the right.

In right to left associativity, the operator at the rightmost part is evaluated first and it moves towards the Following table shows precedence and associativity of operators

OperatorAssociativity
() ++(postfix) – (postfix)Left to right
+(unary) – (unary) ++(prefix) –(prefix)Right to left
*  /  %Left to right
+   –Left to right
=  += -= *= /=  %=Left to right

the operators on the top have the highest precedence and the precedence decreases as we move down in the table. Consider the following example 3+4/2 this expression is evaluated.

In this expression, / has the higher precedence. So, 4/2 will be evaluated first and then the result (2) is added (+) to 3.

So, the result will be 5. If it is needed to change precedence, then one must put parenthesis in the required place.

For example, the above expression is equivalent to the following; 3+(4/2) but if it is written as (3+4)/2, then the precedence is changed.

Now 3 and 4 will be added together and the result is divided by 2. So, the result will be 3 as an integer value.

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.