Hacker News new | ask | show | jobs
by jdblair 908 days ago
I remember when I finally figured out the point of GOSUB (I was maybe 13, so 1986), and why it was more powerful than GOTO. Still no stack, and the only calling convention was that RETURN would take you back to the line after where you called GOSUB.

Writing this words now, I don't know that I ever looked into what happened if you called GOSUB from a GOSUB routine, or how deep you could call. That would imply some sort of stack!

[edited to correct a typo]

4 comments

On an Amstrad,

    10 level=1
    20 GOSUB 40
    30 END
    40 PRINT"Current level: ",level
    50 level=level+1
    60 GOSUB 40
Prints a "Memory full in 50" after printing level 84. At first I thought it dedicated about 168 bytes for GOSUB stack, but the "memory full" happens on the level assignment.

You can erase this stack explicitly by calling `CLEAR` (will also close open files and clear ALL variables).

Does the RETURN statement work correctly on Amstrad when there are multiple subroutines in the call stack? I.e., does every RETURN return to the line after the corresponding GOSUB or after the latest one?
Coverting GOSUB X:RETURN to GOTO X was my first tail-call optimization.

> I don't know that I ever looked into what happened if you called GOSUB from a GOSUB routine

I want to say all BASICs had a stack (not sure about Apple Integer BASIC), or used the CPU stack. Expression evaluation also used it, and if you overflowed it you would get a ?FORMULA TOO COMPLEX error.

Applesoft BASIC allowed nested GOSUBs. I think you could get about 10 deep, if memory serves. You could absolutely do recursive calls. You would have to implement subroutine-local variable scope yourself. (I would have use arrays with an index that incremented at the beginning of each call and decremented before the RETURN.)
Applesoft BASIC was by Microsoft so it is pretty much identical to the other 6502 Microsoft BASICs like on the Commodore and OSI systems. Apple and Commodore both customized their Microsoft BASICs somewhat. If you benchmark Applesoft BASIC and Commodore BASIC, on systems with the same clock speed (eg. 1 MHz), they benchmark the same.
Understanding the point of DATA was also a big breakthrough for me, but that happened earlier.