Friday, December 4, 2009

Operator Precedence in C & CPP

Operator Precedence Chart 
Operator Type                                  Operator                               Associativity
1. Primary Expression Operators     () [] . -> expr++ expr--        left-to-right
2. Unary Operators                        * & + - ! ~ ++expr --expr    right-to-left
                                                           (typecast) sizeof()    
3. Binary Operators                       * / %                                           left-to-right
                                                         + -
                                                          >> <<
                                                          < > <= >=
                                                          == !=
                                                         &
                                                         ^
                                                          |
                                                          &&
                                                          ||
4. Ternary Operator                            ?:                                       right-to-left
5. Assignment Operators     = += -= *= /= %= >>=            right-to-left
                                            <<=  &= ^= |=
6. Comma                                      ,                                                left-to-right

Note: 1,2,3 etc above shows the level of precedence, with 1 being of highest precedence etc.
Associativities are from left to right....like normal arithematic expression, leaving the case  of assignment operator, unary and ternary operator.
  1. Also note that in binary operators arithematic operators are of highest preference....... A for Arirthematic.
  2. Than follow relational operator...R for Relational operator(like < , > etc.)
  3. Than comes bitwise operator....B for Bitwise(eg...
  4. Than logical operator or Boolean operator...L....(eg. && etc)...
So learning way is MARBLE .
Notes:
Exception to MARBLE is bitwise shift operators which has higher precedence than Relational operators.
This can be noted by the fact that....>> has greater precedence than >.
Logical operator ! is of higher precedence being a unary operator.
Postfix is greater than prefix in precedence.
() is greater than [] in precedence...

C++
In case of C++, We have same precedence with some added operators.
1. :: operator is of higher precedence, with precedence = () operator.
2. 
const_cast  , dynamic_cast , reinterpret_cast ,  static_cast ,
typeid
+ we have:
 () Type cast, i.e. (type) expr
sizeof() Size in bytes
new Dynamically allocate storage
 new [] Dynamically allocate array
delete Dynamically free storage
delete [] Dynamically free array 


That's it.

No comments:

Post a Comment