Precedence and Associativity
When an expression can be interpreted in more than one way, there are rules that govern how the expression gets interpreted by the compiler. Such expressions follow C's precedence and associativity rules. The precedence of operators determine a rank for the operators. The higher an operator's precedence, the higher “binding” it has on the operands.
For example, the expression a * b + c can be interpreted as (a * b) + c or a * (b + c), but the first interpretation is the one that is used because the multiplication operator has higher precedence than addition.Associativity determines the grouping of operations among operators of the same precedence. In the expression a * b / c, since multiplication and division have the same precedence we must use the associativity to determine the grouping. These operators are left associative which means they are grouped left to right as if the expression was (a * b) / c.The operators' order of precedence from highest to lowest and their associativity is shown in this table:
Identifier, constant or string literal, parenthesized expression
[] func( arglist ) . -> ++ -- | Left associative |
++ -- & * + - ~ ! sizeof | Right associative |
(type-name) | Right associative |
* / % | Left associative |
+ - | Left associative |
<< >> | Left associative |
< <= > >= | Left associative |
== != | Left associative |
& | Left associative |
^ | Left associative |
| | Left associative |
&& | Left associative |
|| | Left associative |
?: | Right associative |
= *= /= %= += -= <<= >>= &= ^= |= | Right associative |
, | Left associative |
Example #1
int i=2,j=5,k=6,g;
g = i+j*k;
In the above example the evaluation will be taken place in the following way
There are two operators + * Among these two * is having highest precedence. So j*k is evaluated first 5*6=30 Then addition i+30=2+30=32. Final value of g is 32.
Example #2
int x=5,y=30,z=10,w;
w=x*y/z;
Here In the above example * / both are having same precedence. So evaluation is done in left associativity. x*y is done first 5*30=150 then 150/z = 150/10 = 15. The value of w is 15.
Example #3
int i=2,j=5,k=6,g;
g = (i+j)*k;
Here In the above example
There are three operators + * () Among these three () is having highest precedence. So
i+j is evaluated first 2+5 = 7 Then 7*k = 7*6 = 42. So final value of g is 42.
No comments:
Post a Comment