The depths of recursion

Recursion is a tricky topic that, to be honest, I never really quite understood until I took assembly last fall. This summer, a good friend of mine took the class and would send us several questions at random over the course of a couple weeks as she was studying for her final. When recursion came up, I knew I had to remake the spreadsheet I’d done for myself when taking the class. Sadly, the original was long gone, but I’d like to think this one is better. 😀 You may want to open it in a different tab for best visibility.

Something I never really fully understood at first was that recursion is just another function call. Like any other call, once that function completes, your program resumes with the next instruction.

It just happens that with recursion, these function calls are nested. It keeps going until the base case is reached, then resumes execution where it left off. For many functions, there’s nothing after the recursive call so it just completes the function but sometimes there are instructions after which truly demonstrates how recursion works. Looking at this example in MASM, the value is incremented each time rcrsn is called but it prints them in reverse order. If it was printed before the call to rcrsn, it’d print in increasing order. However, it’s after, so what happens is, once the base case is reached you start backtracing to resume execution after the previous function call making it print in decreasing order. Someday I may revisit this in more detail, but this will do for now!

This has a good example of it in C++. http://www.learncpp.com/cpp-tutorial/7-11-recursion/

Leave a Reply

Your email address will not be published. Required fields are marked *