To evaluate postfix, scan left to right: push each operand; for an operator, pop the right operand, then the left, compute, and push the result. The final stack value is the answer. It runs in O(n) with no precedence handling.
Remember
digit -> push
operator -> b = pop(); a = pop(); push(a op b);
end -> result = pop()
Reference
Cheat Sheet
Keep these facts handy while you work with Expression Evaluation in C.
Topic
Detail
Operand
Push
Operator
Pop b, pop a, push a op b
Order
Right operand pops first
Result
Single value left
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Stack Applications.
Example 1 — Evaluate digit expressions
Single-digit operands with + - * /.
C
#include <ctype.h>
#include <stdio.h>
static int eval(const char *e) {
int st[32], top = -1;
for (; *e; e++) {
if (isdigit((unsigned char)*e)) {
st[++top] = *e - '0';
} else {
int b = st[top--];
int a = st[top--];
switch (*e) {
case '+': st[++top] = a + b; break;
case '-': st[++top] = a - b; break;
case '*': st[++top] = a * b; break;
case '/': st[++top] = a / b; break;
}
}
}
return st[top];
}
int main(void) {
const char *tests[] = {"231*+9-", "82/3+", "53+2*"};
for (int i = 0; i < 3; i++) printf("%s = %d\n", tests[i], eval(tests[i]));
return 0;
}
Output
231*+9- = -4
82/3+ = 7
53+2* = 16
How It Works
231*+9-: 3*1=3, 2+3=5, 5-9=-4.
82/3+: 8/2=4, 4+3=7.
53+2*: 5+3=8, 8*2=16.
Edge Cases & Pitfalls
Check these before relying on Expression Evaluation in real programs.
order
Swapped operands
For - and /, a - b is not b - a. Pop b first.
zero
Division by zero
Check b != 0 before dividing.
Remember
Key Takeaways
Push operands.
Pop right then left.
One value remains.
One line: To evaluate postfix, scan left to right: push each operand; for an operator, pop the right operand, then the left, compute, and push the result.
Frequently Asked Questions
Scan left to right, push numbers, and for each operator pop two operands, apply it, and push the result.
It was pushed last, so it is on top of the stack.
Continue with "C Stack Applications" next. Check balanced brackets and see other uses of stacks. The C Stacks hub lists every topic in order.