A stack you already use
After this: See function calls as frames pushed and popped.
On this page · 6 sections · 3 checks
You have now used a stack to match brackets. In fact, you have been relying on a stack since your first function call, even though you could not see it.
Here is a question you may never have asked. When a function finishes, how does the computer know where to go back to?
An everyday picture
Imagine you are cooking and the phone rings. You stop cooking and answer. While you are on the phone, someone knocks at the door. You pause the call and open the door.
When the visitor leaves, you go back to the call. When the call ends, you go back to cooking. The last job you started is the first one you finish. That is last in, first out, and function calls work the same way.
Calls push, returns pop
Each time a function is called, Python or Java records that call in a . A frame holds the function's arguments, its local variables and the place to continue from afterwards. All the frames together form the .
Here is a small program with two functions.
def inner(): print("inner starts") # three frames: the module, outer, inner return 1
def outer(): print("outer starts") x = inner() # outer waits here until inner returns print("outer resumes") return x + 1
print(outer())outer starts inner starts outer resumes 2
public class Calls { static int inner() { System.out.println("inner starts"); // three frames: main, outer, inner return 1; }
static int outer() { System.out.println("outer starts"); int x = inner(); // outer waits here until inner returns System.out.println("outer resumes"); return x + 1; }
public static void main(String[] args) { System.out.println(outer()); }}outer starts inner starts outer resumes 2
Follow the call stack as it runs.
- The program starts. Its own frame is the first one on the stack.
- The program calls
outer. A frame forouteris pushed on top, andouterprintsouter starts. outercallsinner. A frame forinneris pushed on top. There are now three frames, andouteris paused at the linex = inner().innerprintsinner starts.innerreturns 1. Its frame is popped.outeris on top again, so it continues from where it paused, withxset to 1. It printsouter resumes.outerreturns 2. Its frame is popped. The program continues and prints the 2.
So a call pushes a frame, and a return pops a frame. Only the top frame ever runs. Every frame below it is paused, waiting for the frame above it to return.
When the stack runs out
Each frame takes up some memory, and the call stack has a limit. A function can call itself. If nothing ever stops it, each call pushes another frame and no frame is ever popped. In the end the limit is reached, and Python or Java stops the program with an error.
import sys
def forever(n): return forever(n + 1) # nothing stops it: every call pushes another frame
try: forever(0)except RecursionError: print("RecursionError: Python stops at", sys.getrecursionlimit(), "frames")RecursionError: Python stops at 1000 frames
public class Forever { static int forever(int n) { return forever(n + 1); // nothing stops it: every call pushes another frame }
public static void main(String[] args) { try { forever(0); } catch (StackOverflowError e) { System.out.println("StackOverflowError: the thread's stack ran out"); } }}StackOverflowError: the thread's stack ran out
forever calls itself with a bigger number and has no way to stop. The program catches the error so that it can print a message.
Watch it happen
The picture stores numbers, so the frames appear as numbers: 1 is the program, 2 is outer and 3 is inner.
- Push 1The program starts. Its own frame (1) is at the bottom of the call stack.
- Push 2
- Push 3
- Pop
- Pop
- 3·
- 2·
- 1·
- 0·
Run an operation to begin.
Check yourself
What prints, and in what order?
def inner(): print("inner starts") # three frames: the module, outer, inner return 1
def outer(): print("outer starts") x = inner() # outer waits here until inner returns print("outer resumes") return x + 1
print(outer())public class Calls { static int inner() { System.out.println("inner starts"); // three frames: main, outer, inner return 1; }
static int outer() { System.out.println("outer starts"); int x = inner(); // outer waits here until inner returns System.out.println("outer resumes"); return x + 1; }
public static void main(String[] args) { System.out.println(outer()); }}At the moment inner starts is printed, which frames are on the call stack, from bottom to top?
forever(n) calls forever(n + 1) and has no way to stop. What happens?
Connect
- Describe a call as a frame pushed on the call stack, and a return as that frame popped.
- Say which frames are on the stack at a given line, from bottom to top.
- Say what happens when a function keeps calling itself and never stops: RecursionError in Python, StackOverflowError in Java.