Operators Precedence in C++

C++ Operators Precedence

The operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated first.

Example

Consider the following expression:

int x =10+4*3;

Here, the multiplication has higher precedence than addition, so 4 * 3 is evaluated first, resulting in x = 10 + 12, which gives x = 22.

To change the order, use parentheses:

int x =(10+4)*3;

Now 10 + 4 is evaluated first, resulting in x = 14 * 3, which gives x = 42.

C++ Operator Precedence Table

The operators are listed from top to bottom in descending order of precedence:

OperatorDescriptionExample
() [] -> .Function call, Subscript, Member accessarr[0], obj.method(), ptr->member
++ —Increment/Decrementx++, –y
! ~ – +Logical/Bitwise NOT, Unary plus/minus!flag, ~num, -value, +value
* / %Multiplication, Division, Modulusa * b, x / y, n % 2
+ –Addition, Subtractiona + b, x – y
<< >>Bitwise shiftx > 3
< <= > >=Relational operatorsa = y
== !=Equality operatorsa == b, x != y
&Bitwise ANDa & b
^Bitwise XORx ^ y
|Bitwise ORa | b
&&Logical ANDx && y
||Logical ORa || b
?:Ternary conditionalx ? y : z
= += -= *= /= %= &= ^= |= >=Assignment and compound assignmenta = b, x += y, z >>= 2
,Commax = (a, b, c)

Example of Operators Precedence

Try the following example to understand operators 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>usingnamespace std;intmain(){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 ;return0;}

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *