Shop OBEX P1 Docs P2 Docs Learn Events
Why Did This Work (Infinitely nested GOSUBs)? — Parallax Forums

Why Did This Work (Infinitely nested GOSUBs)?

Harry StonerHarry Stoner Posts: 54
edited 2004-10-07 17:37 in BASIC Stamp
I just realized some code I have that seems to work great on a BS2p24 is wrong. I have a GOSUB where I meant to use a GOTO. This should result in infinite recursion. In many programming environments I would blow the stack space in a matter of seconds. Yet the program seems to function fine. Why?

Main loop of the program is structured like this:

MAIN_LOOP:
GOSUB dosomework
GOSUB dosomethingelse
GOSUB MAIN_LOOP ' should be GOTO!

Just curious. The loop executes continuously about 60 times per second. I will fix this soon.

Another question: how much time would a DEBUG statement waste if the Stamp is not connected to a serial port. e.g. is there any wait logic in the DEBUG command, or would it just clock out the data and be done with it? I also discovered some DEBUG statements in my code that I forgot to remove and just wondered how much time they are taking up/wasting (aside from instruction parsing).

Thanks.

Harry

Comments

  • OrionOrion Posts: 236
    edited 2004-10-06 20:47
    I think it’s because if you nest gosubs too deep it will start from the beginning of the program. Also if it hits a RETURN without a gosub it will also start the whole program over. You could test this by inserting a debug statement before the MAIN_LOOP and in the loop and see what happens.
  • Tracy AllenTracy Allen Posts: 6,658
    edited 2004-10-06 21:13
    An unmatched RETURN will simply go to the top of the program in the current bank. The Stamp does not issue error messages at run time, so that is its way out when the stack is empty. It does not check at compile time to see if there is a stack underflow.

    The DEBUG command will execute the same no matter whether or not anything is there listening to the output.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • allanlane5allanlane5 Posts: 3,815
    edited 2004-10-07 15:41
    The big problem with over-nested GOSUB is the 8th return address back gets 'lost'. So, when you hit the 8th 'RETURN' statement, the program has nowhere to go. In that case, it restarts the program.

    Your case, on the other hand, NEVER un-wraps that last gosub. So you keep 'rotating' through the return stack, but that has no negative effects.
  • bobhillierbobhillier Posts: 27
    edited 2004-10-07 17:37
    This definatley identifies an interesting trick to consider when you hit the maximum code size barrier and you need to count every byte. This could save a few bytes and allow that last small feature to be inserted.

    This belongs to the collection of cool tricks you collect through painful experience.

    Thanks for sharing it.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    ······ Bob, Ottawa
    W75 54 17·· N45 18 30
    ·········· G16 #27
Sign In or Register to comment.