1.8Stack / postfix evaluation
The idea
A stack machine evaluates an expression by pushing operands and letting each operator work on the top items of the stack.
Think of it like this: A stack of plates: you can only add or remove from the top. An operator takes the top two plates and puts the result back.
Why it exists
No operand addresses are needed, so instructions are tiny. Compilers also like postfix because it needs no brackets or precedence rules.
How it works
- Write the expression in postfix (operands before the operator).
- Scan left to right: operand → PUSH.
- Operator → POP two, compute (second popped is the left operand), PUSH the result.
- At the end, the answer is the only thing on the stack.
Worked example: (3 + 4) × 5 → 3 4 + 5 *
push 3, push 4, + → pop 4 and 3, push 7. push 5, * → pop 5 and 7, push 35.
Now play with it
- →Press Next step and watch the stack grow and shrink.
- →Type your own, e.g.
2 3 4 * +(answer 14).
- Operand 3: PUSH
- Operand 4: PUSH
- Operator +: POP 4, POP 3, compute 3 + 4 = 7, PUSH
- Operand 5: PUSH
- Operator *: POP 5, POP 7, compute 7 * 5 = 35, PUSH
Check yourself
What does the postfix expression 5 1 2 + 4 * + 3 - evaluate to?
Exam notes (the dense version)
Scan left→right; operand → PUSH; operator → POP two, compute, PUSH. Convert infix → postfix to count PUSH/POP or minimum registers.
Previous year questions: Instruction Formats & Addressing Modes (12)
PYQs are grouped by topic, so this is the full set for Instruction Formats & Addressing Modes; try the ones that match this subtopic. Open all 12 on the topic page.