Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Subroutine, Subroutine nesting and Stack memory

  • Difficulty Level : Easy
  • Last Updated : 11 Nov, 2020

1. Subroutine – 
A set of Instructions which are used repeatedly in a program can be referred to as Subroutine. Only one copy of this Instruction is stored in the memory. When a Subroutine is required it can be called many times during the Execution of a Particular program. A call Subroutine Instruction calls the Subroutine. Care Should be taken while returning a Subroutine as Subroutine can be called from a different place from the memory. 

The content of the PC must be Saved by the call Subroutine Instruction to make a correct return to the calling program. 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Figure – Process of subroutine in a program 

Subroutine linkage method is a way in which computer call and return the Subroutine. The simplest way of Subroutine linkage is saving the return address in a specific location, such as register which can be called as link register call Subroutine. 

2. Subroutine Nesting – 
Subroutine nesting is a common Programming practice In which one Subroutine call another Subroutine. 

Figure – Subroutine calling another subroutine 

From the above figure, assume that when Subroutine 1 calls Subroutine 2 the return address of Subroutine 2 should be saved somewhere. So if link register stores return address of Subroutine 1 this will be (destroyed/overwritten) by return address of Subroutine 2. As the last Subroutine called is the first one to be returned ( Last in first out format). So stack data structure is the most efficient way to store the return addresses of the Subroutines. 

Figure – Return address of subroutine is stored in stack memory 

3. Stack memory – 
Stack is a basic data structure which can be implemented anywhere in the memory. It can be used to store variables which may be required afterwards in the program Execution. In a stack, the first data put will be last to get out of a stack. So the last data added will be the First one to come out of the stack (last in first out). 

Figure – Stack memory having data A, B & C 

So from the diagram above first A is added then B & C. While removing first C is Removed then B & A.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!