44
Chapter 3
I
Recursion
Every time you make a function call, your
computer saves the values
for all the variables for that call in memory like this. Next, you print
hello, maggie!
Then you call
greet2(“maggie”).
Again, your
computer allocates a box of memory for this function call.
Your computer is using a stack for these boxes.
The second box is added
on top of the first one. You print
how are you, maggie?
Then you
return from the function call. When this happens,
the box on top of the
stack gets popped off.
Now the topmost box on the stack is for the
greet
function, which
means
you returned back to the
greet
function. When you called the
greet2
function, the
greet
function was
partially completed.
This is
the big idea behind this section:
when you call a function from another
function, the calling function is paused in a partially completed state.
All
the values of the variables for that function are still stored in memory.
Now that you’re done with the
greet2
function, you’re back to the
greet
function, and you pick up where you left off. First you print
getting ready to say bye…
. You call the
bye
function.
45
The stack
A box for that function is added to the top of the stack.
Then you print
ok bye!
and return from the function call.
And you’re back to the
greet
function. There’s nothing else to be done,
so
you return from the
greet
function too. This stack, used to save the
variables
for multiple functions, is called the
call stack
.
Dostları ilə paylaş: