Pushing And Pulling The Stack
When programming in BASIC or machine language, how does pushing and pulling things on the stack affect the return jump?
Thomas McCrossin
The stack is an area of 256 RAM memory bytes that is used to hold return addresses for BASIC GOSUBs and machine language JSRs.
When a GOSUB is encountered while running a BASIC program, the following happens:
- In the simplest terms, the memory address of the next executable statement following the GOSUB is pushed onto the stack. (Specifically, it's the address minus one byte.)
- The branch to the subroutine is taken, and the subroutine is executed.
- When the RETURN is encountered in the subroutine, the return address information is pulled off the stack, program control is returned to that point, and processing continues.
Basically, the same sequence of events is taken when using machine language. When a JSR is encountered, the return information is pushed onto the stack, the branch is taken, and when the RTS (ReTurn from Subroutine) is encountered, the information is pulled from the stack, and control is returned to that place in the program.
When using GOSUBs and JSRs, this stack activity is automatically performed by the computer.
However, you can push and pull stack information yourself. This can be done with the use of the PHA machine language instruction, which pushes the number in the Accumulator onto the stack, and PLA, which pulls a byte off the stack and places it in the Accumulator. Other stack commands available are PHP, which pushes the processor status onto the stack, and PLP, which pulls a byte from the stack and puts it into the status register.
Manipulating the stack can be tricky. However, if, after jumping to a subroutine, you wish to return somewhere else, you can pull the return information off the stack (placed there by the operating system), and replace it with your data using the PHA command.
The stack can also be used as a temporary storage place for data in machine language programming. Instead of storing information in zero page, or some other area, push it onto the stack. When it's needed again, pull it back off. But be careful, because the stack can hold only 256 bytes of information. Also if you RTS before PLAing the byte or bytes off the stack, the return address will be wrong.