So far we have gone through the following operators in C++:

Now let’s first understand what is meant by an expression. An expression is a sequence consisting of variables, constants and operators which specify a computation. That is, an expression can be evaluated to give a result. For example : num1 + 12 and (num1 – 45 ) / 4 + num2 are expressions consisting of variables num1 and num2 which may be of any data type.

In C++, the compiler follows a certain procedure to evaluate such expressions. A particular order of operations is followed. This order depends on the precedence of operators. High precedence operators are evaluated before any low precedence operators.

The following table lists various operators in the order of their precedence starting from highest to lowest.

[su_table]

 Operator Category Operators Precedence Unary !, ++, –, +, – Highest Arithmetic *, /, % +, – Relational <, >, <=, >= ==, != Logical && || Conditional ?: Assignment =, +=, -=, *=, /=, %= Lowest

[/su_table]

Some important points about precedence:

1. Operators on the same row have equal precedence. They are evaluated from left to right in an expression.
2. You can force an expression to be evaluated first by using parenthesis. For example: In (a-b)*c,  a-b will be evaluated first and then multiplied with c.
3. However, if we have a-b*c,  b*c will be evaluated first and then subtracted from a.
4. It is also recommended to use parenthesis  for enhancing the readability of expressions.

The following program illustrates the concepts explained in this lesson.

```//Program to illustrate precedence of operators in C++ and evaluation of expressions

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int a = 5;
int b = 10;
int c = 20;

int res1 = a+b*c/5;

int res2 = (a+b)*c/5;

int res3 = a++ + b - 2;

cout<<"Result 1 : "<< res1 << "\nResult 2 : " << res2 << "\nResult 3 : " << res3 ;

getch();

return 0 ;
}

/* OUTPUT

Result 1 : 45
Result 2 : 60
Result 3 : 13

*/```

In the above program, you can see how operator precedence is used by the compiler to evaluate various expressions. Refer to the precedence table above to evaluate the expressions yourself and verify your answers with the program output.
Here is a live preview of the program. We hope you’re clear with this lesson. Do let us know your queries. Drop you comments below.

ABOUT THE AUTHOR:

Founder & Senior Editor of ChewCode.com and Editor at GizmoBolt.com. Sakshi is currently pursuing MCA. She is a foodie and has a unique love for learning computer programming languages. Follow her on Google + | Facebook | Twitter. Contact her at [email protected] for feedback and sending tips.

Tags: ,