Operator Precedence

 

Operator precedence and associativity in order from HIGHEST to LOWEST:

 

Operator                                             Associativity  Precedence

-------------------------------------------          -------------  ----------

()  []  ->  .                                         Left to Right  Highest

!  ~  ++  --  unary +  unary --  *  &  (type)  sizeof Right to Left     |

*  /  %                                               Left to Right     |

+  -                                                  Left to Right     |

<<  >>                                                Left to Right     |

<  <=  >  >=                                          Left to Right     |

==  !=                                                Left to Right     |

&                                                     Left to Right     |

^                                                     Left to Right     |

|                                                     Left to Right     |

&&                                                    Left to Right     |

||                                                    Left to Right     |

?:                                                    Right to Left     |

=  +=  -=  *=  /=  %=  &=  ^=  |=  <<=  >>=           Right to Left     v

,                                                     Left to Right  Lowest

 

What is the significance of Associativity? 

 

It tells us how to evaluate operations on the same level of the table (either we evaluate them left to right (which is what we are used to doing) or we evaluate them right to left.

 

Consider the following examples.

 

Example 1:

     x + y - z

 

            Noting that the binary operators + and and - are on the same level

            and associate left to right, we evaluate x + y first and then subtract z

            from that result.

 

Example 2:

     !-4

 

This is an almost silly example, but the table tells us that these two operators, ! and unary - associate right to left.  So the answer in this case is 0 (-4 is a non-zero or TRUE value0 and ! applied to a non-zero or TRUE value yields 0 or FALSE.  It is a good idea to always use parenthesis in writing expressions such as this.

 

Example 3:

            x.*p

           

You will probably not encounter this either in this course.  I will just tell you that it has no meaning as it is written because the operator precedence table tells us that the . (the selection operator) has higher precendence than the * (the dereference operator).  We want things to execute in the other order, so we must write

x.(*p)