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:

Operator Description Example
() [] -> . Function call, Subscript, Member access arr[0], obj.method(), ptr->member
++ -- Increment/Decrement x++, --y
! ~ - + Logical/Bitwise NOT, Unary plus/minus !flag, ~num, -value, +value
* / % Multiplication, Division, Modulus a * b, x / y, n % 2
+ - Addition, Subtraction a + b, x - y
<< >> Bitwise shift x > 3
< <= > >= Relational operators a = y
== != Equality operators a == b, x != y
& Bitwise AND a & b
^ Bitwise XOR x ^ y
| Bitwise OR a | b
&& Logical AND x && y
|| Logical OR a || b
?: Ternary conditional x ? y : z
= += -= *= /= %= &= ^= |= >= Assignment and compound assignment a = b, x += y, z >>= 2
, Comma x = (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>
using namespace std;
 
int 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
Advertisements