1. Computing & Technology

Discuss in my forum

C++ Tutorial - About Expressions and Statements

By , About.com Guide

Operator Precedence in C++

Operator Precedence

In expressions like these
   int y = c + a*b;
   int x = d + e/f;
 
It's important to know the precedence of operators. If you enter 5 x 6 + 7 in a calculator you'll get 37. If you enter 7 + 5 * 6 though you'll get 72 as it adds 7 to 5 first to get 12 then multiplies that by 6. (Not in the Windows accessory calculator though)

C++ is not as dependent upon the order of entry. It has preset precedence levels for it's operators. for expressions its easiest to pop things in brackets like this.

   int y = c + (a*b);
   int x = d + (e/f);
 

Table of Precedence Levels 1-4

The number indicates the levels, 1 is the highest and 18 the lowest. L-R means Left to right, R-L means Right to Left.

 1 :: Scope resolution operator 
 1 (expression) Grouping 
 2 () L-R Function call 
 2 () Value construction, that is, type (expression) 
 2 [] Array subscript 
 2 -> Member operator (Indirect)
 2 . Member operator (Direct)
 2 const_cast Specialized cast 
 2 dynamic_cast Specialized cast 
 2 reinterpret_cast Specialized cast 
 2 static_cast Specialized cast 
 2 typeid Type identification 
 2 ++ Increment operator, postfix 
 2 -- Decrement operator, postfix 
 3 (all unary) 
 3 ! R-L Logical negation 
 3 ~ Bitwise negation 
 3 + Unary plus (positive sign) 
 3 - Unary minus (negative sign) 
 3 ++ Increment operator, prefix 
 3 -- Decrement operator, prefix 
 3 & Address 
 3 * Dereference (indirect value) 
 3 () Type cast, i.e. (type) expr 
 3 sizeof() Size in bytes 
 3 new Dynamically allocate storage 
 3 new [] Dynamically allocate array 
 3 delete Dynamically free storage 
 3 delete [] Dynamically free array 
 4 .* L-R Member dereference 
 4 ->* Indirect member dereference 
 

Continued on the next page

©2012 About.com. All rights reserved.

A part of The New York Times Company.