A function is a set of code that performs a specific task and can be used whenever needed just by calling it.
While using multiple function calls or recursion, the concept of a function call is very necessary to be known, for better understanding of the code.
Now, let’s understand the working of function call
Before understanding the working of function call you need some prerequisite knowledge about Program Execution in the CPU, Program Stack, Stack Frame(Activation Record).
- Program Stack: Program Stack is the stack which holds all the function calls, with bottom elements as the main function.
- Stack Frame: Stack Frame is actually a buffer memory that is an element of program stack and has data of the called function ie
- Return Address
- Input Parameter
- Local Variabes
- Register Savings
- Stack Pointer: Stack Pointer is the pointer that points to the top of program stack i.e. the most recent function called.
Now, whenever a function is called a new stack frame is created with all the function’s data and this stack frame is pushed in the program stack, and the stack pointer that always points the top of the program stack points the stack frame pushed as it is on the top of the program stack.
Series of operations when we call a function:
- Stack Frame is pushed into stack.
- Sub-routine instructions are executed.
- Stack Frame is popped from the stack.
- Now Program Counter is holding the return address.
Note: POP instruction in assembly language removes the top of the stack and assign it to the program counter.
Let’s understand with the help of an Example:
In the above instance of calling a function.
- Program Counter points to the next instruction memory location i.e., 104 before executing a function whereas 100 is the memory location of calling function.
- To restore the return address, contents of Program Counter is pushed into the stack. Now address stored in the top of the stack is 104.
- Calling function Execution: Now Program Counter points to 2000 which is the starting address of the subroutine.After execution of all successive instructions in the subroutine, the address is popped from the stack.
- Popping of the stack refers to removing the top of the stack and assigning to the Program Counter. Now Program Counter is holding the return address i.e., 104.
The main motive behind this article to understand the reason behind pushing the return address in the stack. However only pushing of return address into the stack is not sufficient in modern implementation of a function. We need to push the actual and formal parameters before pushing the return address.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.