16 Gosubs 08M

Martin Waller

New Member
I'm not sure why I am limited to 16 gosubs on the 08M processor ? If my GOSUBS never go deeper than the run-time stack then why does it matter how many I have in my code ?
 

hippy

Technical Support
Staff member
It's due to the way the stack is handled.

Because the PICAXE tokens (opcodes) are not of a fixed size they can start anywhere within the 2048 bit memory ( 256x8 ). To store the actual address of the next token after a GOSUB would require pushing 11 bits, so for a four deep stack this would require 44 bits, 6 bytes. That's a lot of SFR (RAM) to use in a constrained processor like the original PICAXE's were.

To reduce the stack size, every GOSUB is given a number (0..15) and it is this number which is pushed to the stack; that only requires four bits, and the stack is reduced to just two bytes of SFR in total. When a RETURN is executed, it pops the number off the stack, and uses a lookup table to determine the address of where it should return to. The lookup table is held in program memory which there is more of than SFR.

This clever trickery has remained the same in the Firmware as the PICAXE range has grown, although the X-parts have an extended stack allowing 256 GOSUB's to be used; eight bits are pushed instead of four.

On average, you can squeeze about 80 lines of code into an 08M, so 16 GOSUB's is a fair chunk of that. In many cases, a program which will fit into 256 bytes doesn't need that many GOSUB's so it's a compromise of limiting GOSUB's while maximising space for other code.

The balance works quite well for most programs, but there are a few circumstances where more GOSUB's would solve particular problems. Clever programming and algorithm redesign can often get around the problem, and one solution is to create your own stack ...

http://www.hippy.freeserve.co.uk/picaxeq2.htm#How_do_I_overcome_the_GOSUB_Limitation

Edited by - hippy on 3/5/2005 5:34:09 AM
 
Top