Postfix Expression Evaluation

The compiler finds it convenient to evaluate an expression in its postfix form. The virtues of postfix form include elimination of parentheses which signify priority of evaluation and the elimination of the need to observe rules of hierarchy, precedence and associativity during evaluation of the expression.

As Postfix expression is without parenthesis and can be evaluated as two operands and an operator at a time, this becomes easier for the compiler and the computer to handle

Evaluation rule of a Postfix Expression states:

  1. While reading the expression from left to right, push the element in the stack if it is an operand.
  2. Pop the two operands from the stack, if the element is an operator and then evaluate it.
  3. Push back the result of the evaluation. Repeat it till the end of the expression.

Algorithm

  1. Create a stack to store operands (or values).
  2. Scan the given expression and do the following for every scanned element.
    1. If the element is a number, push it into the stack
    2. If the element is an operator, pop operands for the operator from the stack.
      Evaluate the operator and push the result back to the stack
  3. When the expression is ended, the number in the stack is the final answer

Let's see an example to better understand the algorithm:

Expression: 456*+

Postfix Evolution
Postfix Expression Evaluation

Program using C