# Expression evaluation in C++

In this tutorial, we are going to learn the evaluation of an expression in C++. An expression can have operands and operators. In C++, the order of operands and operators is very important. Let’s see how we can evaluate an expression with some examples.

## Expression evaluation in C++ with examples

When we are evaluating an expression, we first find the operator with the highest precedence. We calculate the part consisting of that operator and do the same for the operator with the second-highest precedence and so on. When we encounter two or more than two operators with the same precedence, we look for their associativity. If it is left to right, we first calculate for the operator on the left and move to its right and do the same for the rest of the operators. For right to left associativity, we first calculate for the operator on the right and then move to its left and do the same for the rest of the operators.

If you don’t know about operator precedence and associativity, spend some of your time here: Operators in C++

Let’s understand expression evaluation in C++ with a few examples.

#### Example 1: How to evaluate an expression in C++

Expression: 23-56/8*6+34%2

Evaluation: In the above expression, there are five operators:-(+, -, /, *, %).

Precedence of (*, /, %) greater than (+, -). Since precedence of (*, /, %) is the same, we check for their associativity which is left to right. Therefore, we calculate for the (/) which gives the result: 23-7*6+34%2.

Then we calculate for (*) which gives the result: 23-42+34%2.

Then we calculate for (%) which gives the result: 23-42+0.

Now since (+) and (-) have the same precedence and their associativity is from left to right, we first calculate for (-) which gives the result: -19+0.

Then we calculate for (+) which gives the result: -19

The final answer is -19.

#### Example 2: evaluate an expression in C++

Expression: 45+3*9-57%13/++a (where a is a variable with value 5)

Evaluation: In the above expression, there are six operators:-(+, -, *, /, %, ++(prefix))

Precedence of the pre-increment operator is the highest. Therefore it will be calculated first and the result would be: 45+3*9-57%13/6.

Then we calculate for (*) which gives the result: 45+27-57%13/6.

Then we calculate for (%) which gives the result: 45+27-5/6.

Then we calculate for (/) which gives the result: 45+27-0.

Then we calculate for (+) which gives the result: 72-0.

Then we calculate for (-) which gives the result: 72.

The final answer is 72.

#### Example C++ program

See the example program to understand the concept better.

#include <iostream> using namespace std; int main() { int result1,result2; //expression 1 result1=23-56/8*6+34%2; int a=5; //expression 2 result2=45+3*9-57%13/++a; cout<<"Result1 is "<<result1<<endl; cout<<"Result2 is "<<result2<<endl; return 0; }

The output of the above program will be:

Result1 is -19 Result2 is 72

Thank you.

## Leave a Reply