A method call is a transfer of control of a program. When a method is called, the execution of the current program stops, and control is transferred to the method. The address of the previous program’s next instruction is stored to return once the execution of the method completes. A system stack
is used to keep track of each return address.
A stack
follows the LIFO or last-in-first-out order. Each subsequent return address is placed on top of the stack
. When its relevant method call finishes execution, the return address is popped from the stack
, and the program jumps onto that address to continue execution.
The illustration below shows how a stack
works:
Step 1: The stack is initially empty.
Step 2: A push
operation adds an item to the top of the stack. The top shifts one place above its previous position.
Step 3: Each subsequent push adds an item to the top of the stack.
Step 4: A pop
command removes an item from the top-1 position of the stack. The top shifts one place below its previous position.
Consider the program below:
package main import "fmt" func function_one() { fmt.Println("Inside Function One") function_two() fmt.Println("Back in Function One") } func function_two() { fmt.Println("Inside Function Two") } func main() { fmt.Println("First Line in Main") function_one() fmt.Println("Second Line in Main") }
Line 14
.Line 15
.Line 16
.Line 17
is placed in the stack
. The program keeps track of this address so that it returns to it once the method call finishes its execution.The illustration below shows the state of the stack
and program control at this instance:
We will use a random value to represent the address of each instruction in the
stack
.
function_one
, which begins execution from Line 4
.Line 5
.Line 6
.Line 7
is placed in the stack
.function_two
.The illustration below shows the updated state of the stack
and program control:
function_two
begins execution from Line 10
.Line 11
.stack
pops the return address to indicate completion of this method’s execution and transfer control to the previous method.The illustration below shows the updated state of the stack
and program control:
function_one
.Line 7
(the return address). It outputs the statement.stack
pops the return address to indicate completion of this method’s execution and transfer control to the previous method.The illustration below shows the updated state of the stack
and program control:
main
.Line 17
, and normal flow resumes.To conclude:
The next instruction address is placed in the
stack
when a method is called. This serves as the return address.
When a method finishes execution, the return address is popped from the
stack
.
RELATED TAGS
CONTRIBUTOR
View all Courses