StephenHermer.com
Writing, Iguanas, and Electronics

Save and Restore Register

Registers need to be saved before being used inside a function call, and should be restored before returning back from the function call. A reusable routine does not necessarily know that the registers are empty before it uses them, so we my want to push their contents onto the stack, and then pop them back off after the routine is finished.

   INC SP         ; increment the stack pointer.
   MOV A, STACK   ; save the contents of the "A"-register.
   INC SP         ; increment the stack pointer.
   MOV B, STACK   ; save the contents of the "B"-register.

   MOV STACK, B   ; restore the contents of the "B"-register.
   DEC SP         ; decrement the stack pointer.
   MOV STACK, A   ; restore the contents of the "A"-register.
   DEC SP         ; decrement the stack pointer.



Counters and index registers can be saved and restored the same way as other registers, but the updates need to happen outside of the function call.

   INC SP         ; increment the stack pointer.
   MOV PC, STACK  ; save the contents of the Program Counter.

   MOV STACK, PC  ; restore the contents of the Program Counter.
   DEC SP         ; decrement the stack pointer.