C – Precedence and Associativity and Rules

0
8
digitalample eye
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 appears, then the compiler uses left-to-right or right-to-left rule according to operator type.

The process of evaluating 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 right.

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

Following table shows precedence and associativity of operators
Operator
Associativity
() ++(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 highest precedence and the precedence decreases as we move down
in the table. Consider the following example 3+4/2 this expression is evaluated as

C - Precedence & Associativity

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, 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 added together and the result is divided by 2. So, the result will be 3 as an integer value.

LEAVE A REPLY

Please enter your comment!
Please enter your name here