Evaluating postfix expressions
Evaluate a postfix expression in one pass with a stack of operands.
Syllabus says: “Evaluating Postfix Expressions”
On this page · 17 sections
Number → PUSH. Operator → POP TWICE: the FIRST pop is the RIGHT operand. Push the result. The last value left is the answer.
Collecting ingredients on a tray (stack); when a recipe step (operator) comes, you take the top two ingredients, combine them and put the dish back.
Scan the postfix expression left to right; push operands; on an operator pop op2 then op1, compute op1 operator op2 and push the result; at the end the stack holds the value.
Learning objectives
- Evaluate a postfix expression with an operand stack.
- Pop operands in the correct order for − and /.
- Detect invalid postfix expressions.
Prerequisites
Stacks; infix-to-postfix conversion.
Introduction
Postfix was designed for this: read left to right, keep the numbers you have seen on a stack, and whenever an operator appears, apply it to the two most recent numbers. Brackets and precedence never come into it.
Algorithm
- Scan the postfix expression from left to right.
- Operand → push its value.
- Operator op → b ← pop(), a ← pop(), push (a op b).
- At the end exactly one value must remain on the stack; it is the result.
The first value popped is the right operand. For ‘8 4 /’ you pop b = 4, then a = 8, and compute 8 / 4 = 2, not 4 / 8.
Integer or real division?
The model paper (Q11a) asks to evaluate 4*5/3−(4%2)+(1*5)−2 without saying whether / is integer division.
| Symbol | Stack | Postfix |
|---|---|---|
| 4 | empty | 4 |
| * | * | 4 |
| 5 | * | 4 5 |
| / | / | 4 5 * |
| 3 | / | 4 5 * 3 |
| - | - | 4 5 * 3 / |
| ( | - ( | 4 5 * 3 / |
| 4 | - ( | 4 5 * 3 / 4 |
| % | - ( % | 4 5 * 3 / 4 |
| 2 | - ( % | 4 5 * 3 / 4 2 |
| ) | - | 4 5 * 3 / 4 2 % |
| + | + | 4 5 * 3 / 4 2 % - |
| ( | + ( | 4 5 * 3 / 4 2 % - |
| 1 | + ( | 4 5 * 3 / 4 2 % - 1 |
| * | + ( * | 4 5 * 3 / 4 2 % - 1 |
| 5 | + ( * | 4 5 * 3 / 4 2 % - 1 5 |
| ) | + | 4 5 * 3 / 4 2 % - 1 5 * |
| - | - | 4 5 * 3 / 4 2 % - 1 5 * + |
| 2 | - | 4 5 * 3 / 4 2 % - 1 5 * + 2 |
| end | empty | 4 5 * 3 / 4 2 % - 1 5 * + 2 - |
| Symbol | Action | Stack |
|---|---|---|
| 4 | push 4 | 4 |
| 5 | push 5 | 4 5 |
| * | 4 * 5 = 20 | 20 |
| 3 | push 3 | 20 3 |
| / | 20 / 3 = 6 | 6 |
| 4 | push 4 | 6 4 |
| 2 | push 2 | 6 4 2 |
| % | 4 % 2 = 0 | 6 0 |
| - | 6 - 0 = 6 | 6 |
| 1 | push 1 | 6 1 |
| 5 | push 5 | 6 1 5 |
| * | 1 * 5 = 5 | 6 5 |
| + | 6 + 5 = 11 | 11 |
| 2 | push 2 | 11 2 |
| - | 11 - 2 = 9 | 9 |
Postfix: 4 5 * 3 / 4 2 % - 1 5 * + 2 - · Result: 9 (integer division)
With real division, 20 / 3 = 6.6667 and the result is 9.6667. In the exam, write which interpretation you use; % (remainder) only makes sense for integers, which suggests integer arithmetic was intended.
Worked example
| Symbol | Action | Stack |
|---|---|---|
| 3 | push 3 | 3 |
| 2 | push 2 | 3 2 |
| 4 | push 4 | 3 2 4 |
| * | 2 * 4 = 8 | 3 8 |
| 2 | push 2 | 3 8 2 |
| / | 8 / 2 = 4 | 3 4 |
| + | 3 + 4 = 7 | 7 |
| 5 | push 5 | 7 5 |
| 8 | push 8 | 7 5 8 |
| 4 | push 4 | 7 5 8 4 |
| / | 8 / 4 = 2 | 7 5 2 |
| - | 5 - 2 = 3 | 7 3 |
| - | 7 - 3 = 4 | 4 |
Result: 4 (integer division)
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1EvaluatePostfix(P): stack ← empty
- 2for each token t of P (left to right):
- 3if t is an operand: push value(t)
- 4else (t is an operator):
- 5b ← pop(); a ← pop() // b first!
- 6push (a t b)
- 7return pop() // exactly one value must remain
C implementation
postfix_eval.ctested ✓ 400/400 cases/* Evaluation of a postfix expression using a stack — KTU PCCST303, Module 1
* Tokens are whole numbers and the operators + - * / % ^, separated by spaces.
* Integer arithmetic as in C: / truncates toward zero, % takes the sign of the
* dividend. Values are limited to +/- 10^15 to rule out overflow.
* Input : one postfix expression per line.
* Output: "RESULT: value" or "ERROR: reason" */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LIMIT 1000000000000000LL /* 10^15 */
#define MAXSTACK 64
long long stack[MAXSTACK];
int top = -1;
/* Returns 1 and stores the result in *r, or returns 0 with *err set. */
int apply(long long a, char op, long long b, long long *r, const char **err) {
switch (op) {
case '+': *r = a + b; break;
case '-': *r = a - b; break;
case '*':
if (a != 0 && llabs(b) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
*r = a * b; break;
case '/': if (b == 0) { *err = "division by zero"; return 0; } *r = a / b; break;
case '%': if (b == 0) { *err = "division by zero"; return 0; } *r = a % b; break;
case '^':
if (b < 0) { *err = "negative exponent"; return 0; }
if (a == 0 || a == 1) { *r = (b == 0) ? 1 : a; break; }
if (a == -1) { *r = (b % 2 == 0) ? 1 : -1; break; }
*r = 1;
for (long long i = 0; i < b; i++) {
if (llabs(*r) > LIMIT / llabs(a)) { *err = "value too large"; return 0; }
*r *= a;
}
break;
default: *err = "unknown operator"; return 0;
}
if (*r > LIMIT || *r < -LIMIT) { *err = "value too large"; return 0; }
return 1;
}
const char *evaluate(char *line, long long *result) {
top = -1;
for (char *t = strtok(line, " \t\r\n"); t != NULL; t = strtok(NULL, " \t\r\n")) {
if (isdigit((unsigned char)t[0])) {
if (top == MAXSTACK - 1) return "stack overflow";
stack[++top] = strtoll(t, NULL, 10);
} else if (t[1] == '\0' && strchr("+-*/%^", t[0]) != NULL) {
if (top < 1) return "operator needs two operands";
long long b = stack[top--]; /* right operand first! */
long long a = stack[top--];
long long r;
const char *err = NULL;
if (!apply(a, t[0], b, &r, &err)) return err;
stack[++top] = r;
} else return "bad token";
}
if (top != 0) return "invalid postfix expression";
*result = stack[0];
return NULL;
}
int main(void) {
char line[512];
while (fgets(line, sizeof line, stdin) != NULL) {
long long r = 0;
const char *err = evaluate(line, &r);
if (err) printf("ERROR: %s\n", err);
else printf("RESULT: %lld\n", r);
}
return 0;
}
Sample run · model Q11a · real output from gcc
Input (stdin)
4 5 * 3 / 4 2 % - 1 5 * + 2 -
Output (stdout)
RESULT: 9
Complexity
One push or two pops plus one push per token: O(n) time, O(n) stack space.
Detecting invalid expressions
- An operator finds fewer than two values on the stack → too few operands (e.g. ‘4 +’).
- More than one value remains at the end → too many operands (e.g. ‘4 5’).
- Division or % by zero → undefined; report an error.
Common mistakes
- Computing b op a instead of a op b.
- Pushing operators onto the stack (only operands go on it).
- Forgetting to substitute the variable values before starting.
Asked in KTU exams (2)
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Operand → push. Operator → b = pop, a = pop, push a op b.
- Answer = the single value left.
- Show a Symbol | Action | Stack table.
- O(n).
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 3 (Stacks and Queues) §3.6
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)