r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

3

u/AlSweigart Author: ATBS Apr 05 '22 edited Apr 05 '22

I just got done writing a book on recursion. The reason it's mystifying to you is most likely because the tutorials/instructors who taught it didn't explicitly bring up the call stack.

First: A stack is one of the simplest data structures in computer science. It's like a list, but you can only add or remove things to and from the end of the list. We say you "push" data onto the end (or top) of the stack and "pop" data off the top of stack.

Second: Function calls aren't one-way. When you call a function, the program automatically and behind the scenes your program notes where the execution should return to when the function call returns. This data is called a frame object, and frame objects are pushed to the top of the call stack when a function is called and popped off the top of the stack when the function returns.

So if you have a function a() that calls b() that calls c(), this is how your program knows that when c() returns, it should go back to b(), and when b() returns, it should go back to a(). Here's a brief Python program:

def a():
    print('Start of a()')
    b()
    print('End of a()')
def b():
    print('Start of b()')
    c()
    print('End of b()')
def c():
    print('Start of c()')
    print('End of c()')
a()

When we run it, notice it goes A-B-C-C-B-A:

Start of a()
Start of b()
Start of c()
End of c()
End of b()
End of a()

This is why stacks are called a LIFO or last in, first out. The last thing pushed to the stack is the first thing popped off it.

When we call a(), a frame object (I'll call it a) is pushed to the top of the stack, then when b() is called a frame object (I'll call it b) is pushed and becomes the new top of the stack. Then b() calls c() which creates a c-frame object to push to the top of the stack. When c() returns, the c-frame object is popped off, then when b() returns, the b-frame object is popped off, then when a() returns the a-frame object is popped off and the call stack is empty and our program is back in the global scope, outside of all functions. (Or, if you're in a program written in C which has a main() function, returning from main() means the program terminates.)

One thing to keep in mind: the execution is always in the function call at the top of the stack. This is why when c() returns to b(), the c frame object pops off and the old b frame object under it is now at the top.

It's a bit confusing because the call stack handled behind the scenes. You can't point to a place in your source code where the call stack is. It's either automatically handled by the interpreter or the code for it is added to your program by the compiler.

Now, if you have a recursive function, the function is calling itself. So the call stack has frame objects for the same function but that's okay because remember that the frame objects represent function calls and not functions. Say we have a factorial function:

def fact(n):
    if n == 1:
        return 1
    else:
        return n * fact(n - 1)

When we call fact(3), a new frame object (I'll call it fact-3) is popped to the top of the call stack and the execution enters the fact() function. This ends up running return n * fact(n - 1), but before it can do that, it needs to call fact(2).

A new frame object (I'll call it fact-2) is created and popped to the top of the stack. This is just like a() calling b(), except in this case a and b are the same function: it's fact() calling fact().

Here's the other thing that trips people up: each frame object stores a separate copy of the local variables. Rather than think of the local variables like n as local to the function, they are actually local to a specific function call. This means there are multiple n variables: in the fact-3 frame object n is set to 3 and in the fact-2 frame object n is set to 2. They have the same name, but these are two separate variables storing two separate values.

This is a major point of confusion for people learning recursion. Seriously, people are always thrown off because when you look at the code, you only see one n variable and it's easy to overlook the fact that there's actually one n variable for each function call. This is why recursion looks like magic: you expect fact(5) to do 5 x 4 x 3 x 2 x 1 but all you see is n * fact(n - 1) and people don't know where the full multiplication is taking place.

Anyway, fact(2) has to call fact(1) (creating a fact-1 frame object), which returns 1. When it returns, the fact-1 frame object is popped off the stack. Now we're back in the previous call to fact(), but it's the fact-2 frame object where n is set to 2. The return n * fact(n - 1) now looks like return 2 * 1 because fact(n - 1) returned 1 and the local n variable is 2.

This makes our fact(2) call return 2 * 1, that is, 2, and the program (automatically, behind the scenes) pops off the fact-2 frame object and the execution returns to the fact() function again, but in the context of the fact-1 frame object where the local n variable is (and always has been) set to 3. This time the return n * fact(n - 1) is really return 3 * 2. So this fact(3) function call returns 6 and pops the fact-3 frame object off the call stack.

There's nothing left on the call stack at this point, so the program continues running code from whatever point in the global scope called fact(3) and that fact(3) function call has evaluated to 6.

As for where the 3 x 2 x 1 is taking place, the flow control of fact() is simple enough that we can substitute the function calls with that call's return statement:

fact(3)

  |
  V

(3 * fact(2))

  |
  V

(3 * (2 * fact(1)))

  |
  V

(3 * (2 * (1)))

  |
  V

  6

1

u/RenewAi Apr 05 '22

Oh hey what's up Al? Thanks for writing replying to me! Automate the boring stuff with python was my first python tutorial ever, I bought it on udemy like 6 or so years ago and tried to get all my friends to buy it and learn python with me lol.

You are exactly right about other people not teaching the call stack, it was a huge problem for me. Interestingly enough my work around for not understanding recursion was to use iteration and a stack lol.

I really wish I had your explanation when I first tried to learn it, I would have saved so much time and frustration. I'm going to do some practice problems later tonight but I actually think I fully get it now! What an accomplishment.

I didn't know you had a recursion book, I am definitely going to check it out.