![]() |
Forum Index : Microcontroller and PC projects : MMBasic, Subroutine Recursion
Author | Message | ||||
apam Newbie ![]() Joined: 14/05/2021 Location: AustraliaPosts: 6 |
Hi I'm looking at code someone else has written... They have things like: Sub ThisSub print "Doing Stuff" ThisSub End Sub The intention there is so it will go back to the start of the sub after doing stuff. Is that going to cause infinite recursion and exhaust the stack? I'm new in MMBasic, so not sure if it behaves differently to something like C Andrew |
||||
vegipete![]() Guru ![]() Joined: 29/01/2013 Location: CanadaPosts: 1132 |
On a CMM2, if you run this: ThisSub 1 end sub ThisSub n Print "Doing Stuff",n ThisSub n+1 end sub you get: > run Doing Stuff 1 Doing Stuff 2 Doing Stuff 3 Doing Stuff 4 Doing Stuff 5 [many lines chopped out] Doing Stuff 99 Doing Stuff 100 Error in line 5: Too many SUB and FUN > Visit Vegipete's *Mite Library for cool programs. |
||||
JohnS Guru ![]() Joined: 18/11/2011 Location: United KingdomPosts: 4044 |
It's infinite recursion. Some compilers cope (tail recursion optimising) but that's just hiding the fact. John |
||||
CaptainBoing![]() Guru ![]() Joined: 07/09/2016 Location: United KingdomPosts: 2170 |
Welcome Yes. if you invoke the Sub name that will start a new "instance" of it, stack, local variables and all. Soon run out of resources doing that. Could probably do something clever with a Static variable (on the right platform) to keep track of it all but why break your back? If the intention is to simply go back to the top of the code inside then structuring with a Do/Loop etc. is probably the best method as they are easy to jump out of and look cute - I doubt the user wants to stay in the Sub forever. You could be a free-thinker and use a GoTo ![]() Edited 2021-05-22 16:02 by CaptainBoing |
||||
MustardMan![]() Senior Member ![]() Joined: 30/08/2019 Location: AustraliaPosts: 175 |
I'm guessing that the sample snippet has some terminating condition inside it which has not been shown, otherwise it does not make programmatic sense. Recursion is a stack-heavy (and compute heavy) way of performing things, but sometimes it is the best way. One example that springs to mind is filling an odd-shaped polygon by specifying a point inside and then recursively stepping further and further out to an edge, and then dropping back to the previous level, and repeat until filled. Cheers, |
||||
apam Newbie ![]() Joined: 14/05/2021 Location: AustraliaPosts: 6 |
Thanks all, I modified the code to use loops. I just didn't want to assume it was an error given that I am new to MMBasic. |
||||
![]() |
![]() |
The Back Shed's forum code is written, and hosted, in Australia. | © JAQ Software 2025 |