Wednesday, November 30, 2011

Operator Precedence and Associativity

An expression may be a combination of multiple operators. In such expressions with the combination of multiple operators, how are the expressions evaluated ? Here a rule comes into play. Its called operator precedence. Here, the operators are grouped and each group is given a specific level of precedence.

For example:
4 + 5 * 12

Here * has higher precedence than +. Thus the evaluation would be done as follows :
4 + 5 * 12
4 + 60
64

The higher level of precedence means those operators are evaluated first in the expression. But what would happen if the expression consists of operators with same precedence level. Here again, another rule known as 'Associativity' is applied. Some may be left to right and some may be right to left.

For example, consider the following expression :
4 + 5 - 2

Here both + and - has same precedence level and there may arise a confusion how this will be evaluated. According to Associativity , + and - have left to right associativity. Thus evaluation is done as follows :
4 + 5 - 2
9 - 2
7

The following table gives the operators and their associativity: (the precedence level decreases from top to bottom). Higher the priority, the order the expression is evaluated.
OperatorsDescriptionAssociativity
()
[]
. and ->
++ and --
Function Call / Parentheses
Array Subscript
Member Selection
Postfix Increment/Decrement
Left to Right
++ and --
sizeof
&
*
+ and -
~
!
(type)
Prefix Increment/Decrement
sizeof
Address of
Value of
Unary Plus/Minus
Bitwise Complement
Logical Negation
Type cast
Right to Left
*
/
%
Multiplication
Division
Modulus
Left to Right
+
=
Addition
Subtraction
Left to Right
<<
>>
Left Shift
Right Shift
Left to Right
<
<=
>
>=
Less than
Less than or Equals
Greater than
Greater than or Equals
Left to Right
==
!=
Equality
Inequality
Left to Right
&Bitwise ANDLeft to Right
^Bitwise XORLeft to Right
|Bitwise ORLeft to Right
&&Logical ANDLeft to Right
||Logical ORLeft to Right
?:Conditional ExpressionRight to Left
=
*=
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
Assigment OperatorsRight to Left
,Comma / Sequential EvaluationLeft to Right

No comments:

Post a Comment