Mail me with a quote to go here...
Created: 6th October 1999
Last Modified: 27th November 1999
This page explains the basics of the stack and the two associated instructions, PUSH and POP. The PUSH and POP instructions can be very useful - they allow you to save the value of a register. However, they are also over used. This page also introduces a new register, SP or the Stack Pointer.
Think of a pile of trays, each with a number on (this is a stupid example, but some programmers thought it sounded cute, so that's where the names come from). Then you take another tray with a number on it and PUSH it onto the top of the pile. Later on you come back and POP the same tray off the top of the pile.
Confused? OK, the stack is an area of memory. You can PUSH things onto the top of it and POP things off the top of it. The last thing you PUSH on is the first thing that is POPped off. Let's see an example:
» We start off with an empty stack.
» We then PUSH the number $1234 onto it.
» Later on we also PUSH the number $abcd onto it.
» And then the number $0fb3.
» We then decide to POP a number from the stack. As the stack is LIFO (Last In First Out) we get the 'top' value, $0fb3, leaving the stack looking like:
» We then PUSH another value onto the stack, $0003 (note that I am only expressing all these numbers in hexadecimal because I think that way...), getting:
» We then POP a value from the stack. As before, this is the last number that we PUSHed, $0003.
» We then POP from the stack again, geting $abcd.
» We then POP the final number from the stack, $1234. As this was the first number we PUSHed, it is the last value we get when POPping, leaving us with an empty stack.
The PUSH instruction takes the general form push rr, where rr is
a register pair (af, bc, de or hl). The POP instruction takes the general form
pop rr. For example:
push af push bc pop de push hl pop hl pop af
Of course you are allowed other instructions in between the PUSHes and POPs. The following are not allowed though:
push a ; Can't push single register pop be ; be is not a register pair push $1234 ; Can't push a number
Note that when you PUSH a register pair onto the stack you can POP it back into a different register pair - you do not have to POP it back into the register pair it came from.
In my pictures above I used a red arrow to point to the top value of the stack. On the calculator there is a register which does the same thing as the arrow, called SP (short for Stack Pointer). You can't do much with it, but it is there.