Appendices

Operator Precedence



The precedence order of the operators covered in these notes is important in the evaluation of compound expressions.  A compound expression consists of several sub-expressions.  Different orders of evaluation are possible in such expressions.  That is, the results of evaluating the entire compound expression depend on the order of evaluating its sub-expressions. 

To ensure unique evaluation of all compound expressions, C++ defines rules of precedence on the operators in a compound expression.  This order is from top to bottom in the table shown below.  The operators associate operands in each sub-expression as noted in the right column, mostly from left to right.

Operator Associate From
:: left to right
[ ] . -> ++ (postfix) -- (postfix) left to right
 ++ (prefix) -- (prefix) + - & ! (all unary) 
new new[] delete delete[] (type), type()
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
= += -= *= /= %= right to left
?: left to right
, left to right

The scope resolution operator :: has the highest precedence.  An expression containing this operator is always evaluated first. 

We can change the order of evaluation within a compound expression by enclosing a sub-expression in parentheses.  That is, we use (sub-expression) to evaluate sub-expression before applying the rules of precedence to the entire expression. 

For example,

   2 + 3   * 5 evalues to 2 + 15 evalues to 17
 ( 2 + 3 ) * 5 evalues to 5 * 5  evalues to 25
   Printer Friendly Version of this Page print this page     Top  Go Back to the Top of this Page
Previous Reading  Previous: ASCII Collating Sequence Next: Relation Between C++ and C   Next Reading


  Designed by Chris Szalwinski   Copying From This Site   

Creative Commons License