Re: LZ: Push And Pop


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

Re: LZ: Push And Pop



On Sat, 3 Aug 1996, Josh Pieper wrote:


[snip]
> Ex:
> 
>   ld bc,$0010        > Parameter a
>   push bc
>   ld de,$0020        > Parameter b
>   push de
>   CALL_(Add)
> 
>   pop de               > de now contains $10+$20==$30!!
> 
>   Rest Of Program
> 
> ; Add Routine
> Add:
>   pop hl                > In this example puts a $20 in hl
>   pop de               > Puts $10 in de
>   add hl,de
>   push hl              > The stack can also be used to return values
>   ret
> 
> 
> If you have any further questions on the subject post them to this list 
> or email me at:
> 
> Josh Pieper
> ppieper@nemonet.com  


You left out one important detail... When you call a routine, that address
to return to is pushed onto the stack.  When you return, the value on the
top of the stack is popped off, and the cpu jumps to that address.  As a
result the example above will crash.  This version, however, should not.


ProgStart:
	ld bc, $0010	;first number to add
	ld de, $0020	;second number to add
	push bc
	push de
	CALL_(Add)	;Add returns the added number on the stack
	pop de		;de contains $0030, or $10 + $20
	;rest of program


Add:
	pop bc		;save address to return to in bc
	pop de		;second parameter now in de
	pop hl		;first parameter in hl
	add hl, de	;hl is now the sum
	push hl		;return value
	push bc		;push address to return to
	ret


Just remember: ALWAYS save the value on the top of the stack when you
enter a subroutine that does stack manipulation, unless you understand the
stack well and are sure that you don't want to save the address (and don't
mind crashing your calc during testing ;-) ).


	-Shmuel
<pre>
--
<a href="mailto:shmuelp@poboxes.com">mailto:shmuelp@poboxes.com</a>     http://www.netforward.com/POBoxes/?shmuelp
</pre>


References: