Problems in Expression Evaluation

For Complete YouTube Video: Click Here

In this class, we will try to understand Problems in Expression Evaluation.

We have covered Arithmetic, Assignment, Increment- Decrement, Bitwise, Shift, Ternary, Relational, and Logical Operators in our previous classes.

To understand the problems in expression evaluation, let us consider the expressions given below.

2 + 3 * 5
5 * 3 + 2
2 + 3 – 4

Let us consider the first and second expression.

If we try to evaluate the first expression and assess it from left to right, the output is 25.

Similarly, if we assess the second expression from left to right, the output is 17.

Both the expression have the same number with the same operands in between.

As we are executing the expressions from left to right, both are evaluating different results.

How can the expressions be evaluated?

The expressions are evaluated by precedence’s and associativity of the operators.

In our primary school math, we learned that each operator has some precedence when compared with others.

From that knowledge, we can say that multiplicative operators [*, /, %] has higher precedence than additive operators [+, -].

So the above expressions 2 + 3 * 5, 5 * 3 + 2 will evaluate the same result 17 by considering the precedence.

Similarly, consider the third expression 2 + 3 – 4.

All the operators have precedence.

How will we evaluate this kind of expressions?

If all the operators in the expression have the same precedence, we will consider associativity.

The associativity of the additive operators is from left to right.

So, 2+3 is evaluated first.

Now we will evaluate 5-4.

How the C Compiler will evaluate the expression?

C Compiler or any Compiler will evaluate the expression by using Precedence and Associativity table.

In the next class we will cover how C compiler will execute the expression by using Precedence and Associativity table.