adsense


Saturday, 21 November 2015

C++ LANGUAGE OPERATORS PRECEDENCE PAGE 46

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE OPERATORS PRECEDENCE





Operators Precedence in C++ 

Operator precedence determines the grouping of terms in 
an expression. This affects how an expression is evaluated. 
Certain operators have higher precedence than others; for 
example, the multiplication operator has higher precedence 
than the addition operator: 
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 
because operator * has higher precedence than +, so it first 
gets multiplied with 3*2 and then adds into 7. 
Here, operators with the highest precedence appear at the 
top of the table, those with the lowest appear at the bottom. 
Within an expression, higher precedence operators will be evaluated first. 

Operator             Associativity  

Postfix   () [] -> . ++ - -    Left to right  
Unary      + - ! ~ ++ - - (type)* & sizeof   Right to left  
Multiplicative    * / %   Left to right  
Additive    + -   Left to right  
Shift    << >>   Left to right  
Relational    < <= > >=   Left to right  
Equality    == !=   Left to right  
Bitwise AND   &   Left to right  
Bitwise XOR   ^   Left to right  
Bitwise OR   |   Left to right  
Logical AND   &&   Left to right  
Logical OR   ||   Left to right  
Conditional   ?:   Right to left  
Assignment   = += -= *= /= %=>>= <<= &= ^= |=   Right to left  
Comma          ,   Left to right  

Try the following example to understand operator’s precedence 
concept available in C++. Copy and paste the following C++ program 
in test.cpp file and compile and run this program. 
Check the simple difference with and without parenthesis. 
This will produce different results because (), /, * and + 
have different precedence. Higher precedence operators will 
be evaluated first: 

#include <iostream> 

using namespace std; 
  
main() 
{ 
   int a = 20; 
   int b = 10; 
   int c = 15; 
   int d = 5; 
   int e; 
  
   e = (a + b) * c / d;      // ( 30 * 15 ) / 5 
   cout << "Value of (a + b) * c / d is :" << e << endl ; 
 
   e = ((a + b) * c) / d;    // (30 * 15 ) / 5 
   cout << "Value of ((a + b) * c) / d is  :" << e << endl ; 
 
   e = (a + b) * (c / d);   // (30) * (15/5) 
   cout << "Value of (a + b) * (c / d) is  :" << e << endl ; 
 
   e = a + (b * c) / d;     //  20 + (150/5) 
   cout << "Value of a + (b * c) / d is  :" << e << endl ; 
   
   return 0; 
} 
When the above code is compiled and executed, it produces the following result: 
Value of (a + b) * c / d is :90 
Value of ((a + b) * c) / d is  :90 
Value of (a + b) * (c / d) is  :90 
Value of a + (b * c) / d is  :50 









No comments: