Re: LZ: Push And Pop


[Prev][Next][Index][Thread]

Re: LZ: Push And Pop



On Sat, 3 Aug 1996, Patti Balsan wrote:


> I am an aspiring ZShell programer and I was wondering if anybody could
> tell me what "push" and "pop" do during a program and how I could use them
> in one of mine.


Push and pop are stack instructions.  First you have to know about
the stack.  I don't have my book handy so I'm probably going to get
some of this wrong.  I'm sure I'll get corrected.  Most of it will
be right, though.


The stack is called a stack because it's like the stack of dishes
sitting on a spring in a restaurant.  You put a dish on top, then
another and another, and then you take off the top one when you
need it.  Because of the spring, the top one stays at about the
same level no matter how many dishes you add (push) or remove
(pop) from the stack.


There is a register, SP, in the Z80 that contains the address of
the stack.  It "points" to the top of the stack.  (actually in
the Z80 the stack is upside down just to help it be a little more
confusing).  When you push bc, the cpu decrements the stack by one,
puts the contents of b at that address, then decrements by one again
and puts the contents of b at that address.  This is usually done
to save the contents of bc while you use the register for something
else.  Later you can restore its contents by pop bc.  That gets
the value into c that sp points to (the top value) and then
increments sp and gets the next value into b and increments it again.


The stack is also used by call and return.  When you call a routine,
it pushes the current pc (the address of the next instruction) on
the stack and then jumps to the subroutine.  Return pops that
same value back into the pc.  Because of this, and for a lot of
other reasons all involving coordination, you must do a pop for
every push in a routine so that the stack is like you left it before
you return.  If you don't, the computer crashes and this can be
a tricky thing to figure out.  It's especially difficult because
it doesn't always crash at the return.  The screwed up stack might
just work wrong, but still work, for quite a while.


Just remember, a pop for every push.  Another thing to remember is
that the stack is limited in size.  How big it is depends on the
system and the program, but if you don't knwo the size of it, don't
use much of it and even then, watch for problems.


When you reach the point where you're comfy with the stack and can
use it to get good results and can do it without causing problems,
that's sort of a milestone in becomming an assembly programmer.


Barry


References: