The Wayback Machine - https://web.archive.org/web/20240831193900/https://www.geeksforgeeks.org/subroutine-subroutine-nesting-and-stack-memory/
Open In App

Subroutine, Subroutine nesting and Stack memory

Last Updated : 29 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In computer programming, Instructions that are frequently used in the program are termed Subroutines. This article will provide a detailed discussion on Subroutines, Subroutine Nesting, and Stack Memory. Additionally, we will explore the advantages and disadvantages of these topics. Let’s begin with Subroutines.

What is a Subroutine?

A set of instructions that are used repeatedly in a program can be referred to as a 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 a 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. 

Process of a subroutine in a program 

Process of a subroutine in a program 

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

Advantages of Subroutines

  • Code reuse: Subroutines can be reused in multiple parts of a program, which can save time and reduce the amount of code that needs to be written.
  • Modularity: Subroutines help to break complex programs into smaller, more manageable parts, making them easier to understand, maintain, and modify.
  • Encapsulation: Subroutines provide a way to encapsulate functionality, hiding the implementation details from other parts of the program.

Disadvantages of Subroutines

  • Overhead: Calling a subroutine can incur some overhead, such as the time and memory required to push and pop data on the stack.
  • Complexity: Subroutine nesting can make programs more complex and difficult to understand, particularly if the nesting is deep or the control flow is complicated.
  • Side Effects: Subroutines can have unintended side effects, such as modifying global variables or changing the state of the program, which can make debugging and testing more difficult.

What is Subroutine Nesting?

Subroutine nesting is a common Programming practice In which one Subroutine calls another Subroutine.

Subroutine calling another subroutine 

A 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 the link register stores the return address of Subroutine 1 this will be (destroyed/overwritten) by the 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. 

Return address of subroutine is stored in stack memory

The Return address of the subroutine is stored in stack memory

What is Stack Memory?

A Stack is a basic data structure that can be implemented anywhere in the memory. It can be used to store variables that may be required afterwards in the program Execution. In a stack, the first data put will be the 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). 

Stack memory having data A, B & C

Stack memory having data A, B & C

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

Advantages of subroutine nesting and Stack Memory

  • Flexibility: Subroutine nesting allows for the creation of complex programs with many levels of abstraction, making it easier to organize code and reuse functionality.
  • Efficient use of memory: Stack memory is used to allocate and deallocate local variables, allowing for efficient use of memory resources.
  • Error handling: Stack Memory can be used to keep track of the state of the program, allowing for recovery from errors and exceptions. 

Disadvantages of Subroutine Nesting and Stack Memory

  • Stack overflow: If too many subroutine calls are nested or if the local variables are too large, the stack memory can overflow, causing the program to crash.
  • Security vulnerabilities: Stack-based buffer overflows can be exploited by attackers to execute malicious code or crash the program.
  • Performance: The use of stack memory can impact program performance, particularly if the program requires a large amount of memory or if the stack needs to be frequently accessed.

Subroutine, Subroutine nesting and Stack Memory – FAQs

1. How subroutine nesting is handled with the help of stack?

Prior to calling the subroutine, the calling program places the four parameters onto the stack. Next, the call instruction is executed, causing the return address to be added to the stack. At this point, the stack pointer (SP) points to the return address, and the first instruction of the subroutine is ready to execute.

2. Why do we need stack and subroutine?

By using a stack, it’s possible to store multiple entries and have multiple subroutines active simultaneously. If one subroutine calls another, the microprocessor must keep track of the return addresses of both subroutines in the order they were called.

3. Does Subroutines with nested levels can be accessed from other subroutines?

Yes, subroutines having nested levels can easily access variables from other subroutines, just a condition that these variables are within the scope of the subroutine.

4. Why return statement is used in Subroutine?

The “return” statement is used to exit from a subroutine and it also provides value back to the calling code. It also maintains the flow of execution by giving control to the caller.


Previous Article
Next Article

Similar Reads

Return from Subroutine and Return from Interrupt
In this article, we will discuss the Return from Subroutine and Return from Interrupt and will explain in detail and finally conclude with Difference between Return from Subroutine and Return from Interrupt. Let's discuss it one by one. Return from Subroutine : To return from a subroutine is to return execution of code to the point it was before th
3 min read
Difference between Random Access Memory (RAM) and Content Addressable Memory (CAM)
Random Access Memory (RAM) is used to read and write. It is the part of primary memory and used in order to store running applications (programs) and program's data for performing operation. It is mainly of two types: Dynamic RAM (or DRAM) and Static RAM (or SRAM). RAM is made up of small memory cells that are arranged in a grid pattern. Each cell
4 min read
Difference between Virtual memory and Cache memory
Cache Memory: Cache memory increases the accessing speed of CPU. It is not a technique but a memory unit i.e a storage device. In cache memory, recently used data is copied. Whenever the program is ready to be executed, it is fetched from main memory and then copied to the cache memory. But, if its copy is already present in the cache memory then t
2 min read
Difference between Uniform Memory Access (UMA) and Non-uniform Memory Access (NUMA)
Multiprocessors can be categorized into three shared-memory model which are: Uniform Memory Access (UMA)Non-uniform Memory Access (NUMA)Cache-only Memory Access (COMA) Uniform Memory Access (UMA): In UMA, where Single memory controller is used. Uniform Memory Access is slower than non-uniform Memory Access. In Uniform Memory Access, bandwidth is re
4 min read
Difference between Byte Addressable Memory and Word Addressable Memory
Memory is a storage component in the Computer used to store application programs. The Memory Chip is divided into equal parts called as "CELLS" . Each Cell is uniquely identified by a binary number called as "ADDRESS" . For example, the Memory Chip configuration is represented as '64 K x 8' as shown in the figure below. The following information ca
3 min read
Random Access Memory (RAM) and Read Only Memory (ROM)
Memory is a fundamental component of computing systems, essential for performing various tasks efficiently. It plays a crucial role in how computers operate, influencing speed, performance, and data management. In the realm of computer memory, two primary types stand out: Random Access Memory (RAM) and Read-Only Memory (ROM). Understanding the diff
8 min read
Memory Stack Organization in Computer Architecture
A stack is a storage device in which the information or item stored last is retrieved first. Basically, a computer system follows a memory stack organization, and here we will look at how it works. A portion of memory is assigned to a stack operation to implement the stack in the CPU. Here the processor register is used as a Stack Pointer (SP). The
4 min read
Memory mapped I/O and Isolated I/O
As a CPU needs to communicate with the various memory and input-output devices (I/O) as we know data between the processor and these devices flow with the help of the system bus. There are three ways in which system bus can be allotted to them : Separate set of address, control and data bus to I/O and memory.Have common bus (data and address) for I
5 min read
2D and 2.5D Memory organization
The internal structure of Memory either RAM or ROM is made up of memory cells that contain a memory bit. A group of 8 bits makes a byte. The memory is in the form of a multidimensional array of rows and columns. In which, each cell stores a bit and a complete row contains a word. A memory simply can be divided into this below form. 2n = N where n i
4 min read
Read and Write operations in Memory
A memory unit stores binary information in groups of bits called words. Data input lines provide the information to be stored into the memory, Data output lines carry the information out from the memory. The control lines Read and write specifies the direction of transfer of data. Basically, in the memory organization, there are [Tex]2^{l} [/Tex]me
3 min read
Difference between Memory based and Register based Addressing Modes
Prerequisite - Addressing Modes Addressing modes are the operations field specifies the operations which need to be performed. The operation must be executed on some data which is already stored in computer registers or in the memory. The way of choosing operands during program execution is dependent on addressing modes of instruction. "The address
4 min read
Locality of Reference and Cache Operation in Cache Memory
Locality of reference refers to a phenomenon in which a computer program tends to access same set of memory locations for a particular time period. In other words, Locality of Reference refers to the tendency of the computer program to access instructions whose addresses are near one another. The property of locality of reference is mainly shown by
4 min read
Memory Hierarchy Design and its Characteristics
In the Computer System Design, Memory Hierarchy is an enhancement to organize the memory such that it can minimize the access time. The Memory Hierarchy was developed based on a program behavior known as locality of references. The figure below clearly demonstrates the different levels of the memory hierarchy. Why Memory Hierarchy is Required in th
5 min read
Difference between Simultaneous and Hierarchical Access Memory Organisations
In the Computer System Design, Memory organisation is primarily divided into two main types on the basis of the manner in which CPU tries to access different levels of Memory. These two types include Simultaneous Access Memory Organisation and Hierarchical Access Memory Organisation. Let us understand the difference between the two from the followi
2 min read
Difference between Random Access Memory (RAM) and Hard Disk Drive (HDD)
A person novice to computers often is in confusion between Random Access Memory (RAM) and Hard Disk Drive (HDD). Here we draw comparisons between the two. Similarities between RAM and HDD : Both are used for storage of data.Both are physical components of the computer machine.Both RAM and HDD are measured in bytesBoth RAM and HDD can affect the per
3 min read
Differences between Associative and Cache Memory
1. Associative Memory: The time required to find an object stored in memory can be significantly reduced if the stored data can be identified by the content of the data for its own use rather than by access. A memory unit accessed by a material is known as an associative memory or a content addressable memory (CAM). This type of memory is accessed
2 min read
Difference between Memory Mapped IO and IO Mapped IO with reference to 8085 microprocessor
Introduction : In a microprocessor system, there are two methods of interfacing input/output (I/O) devices: memory-mapped I/O and I/O mapped I/O. In memory-mapped I/O, input/output devices are mapped to the memory address space of the microprocessor. This means that the I/O devices are treated like memory locations and can be accessed using the sam
4 min read
Advantages and Disadvantages of Flash Memory
Flash memory is an evolving technology that's finding its way into our lives on an increasing scale. Flash-memory technology is ubiquitous. Like most things associated with computers, non-volatile storage sticks have a specific set of benefits and drawbacks. Having a basic idea of those parameters allows the buyer to form a more informed choice abo
5 min read
Difference Between Efficiency and Speedup in Cache Memory
Pre-requisites: Cache Memory Performance Cache memory can improve both the efficiency and speed of a computer by reducing the number of accesses to main memory and allowing the CPU to access data more quickly. EfficiencyCache memory is a type of high-speed memory that is built into a computer's central processing unit (CPU) or located close to it.
3 min read
Difference Between Sequential and Random Memory Access
Magnetic tapes and other sequential access storage technologies read and write data linearly. This implies that the gadget has to process all previous data before accessing a specific piece of data. On a cassette tape, for instance, you have to fast-forward through the first four tracks to hear the fifth song. It may take a while to retrieve data u
6 min read
What is Memory Slot? Function and Definition
Memory Slot: A memory slot is a connector inside a computer that allows you to insert a memory module (RAM) to increase or upgrade the machine's memory capacity. Memory slot, also known as a RAM slot or memory socket, is a physical interface on a computer motherboard that holds RAM (Random Access Memory) modules. The number of memory slots can vary
6 min read
Difference between Register and Memory
1. Register : Registers are the smallest data holding elements that are built into the processor itself. These are the memory locations that are directly accessible by the processor. It may hold an instruction, a storage address, or any kind of data such as a bit sequence or individual characters. For example, an instruction may specify that the co
2 min read
Difference between Cache Memory and Register
1. Cache Memory: The cache is a smaller and fast memory component in the computer which is inserted between the CPU and the main memory. To make this arrangement effective. The cache needs to be much faster than the main memory. This approach is more economical than the use of fast memory devices to implement the entire main memory. 2. Register: Re
2 min read
Difference between Shared Memory Model and Message Passing Model in IPC
Inter-Process Communication (IPC) is a critical aspect of modern operating systems, enabling processes to exchange data and synchronize their actions. Two primary models for IPC are the Shared Memory Model and the Message Passing Model. In the modern operating system, the Inter-Process Communication (IPC) is a very important element. It enables som
4 min read
Magnetic Tape memory
Magnetic drums, magnetic tape and magnetic disks are types of magnetic memory. These memories use property for magnetic memory. Here, we have explained about magnetic tape in brief. Magnetic Tape memory : In magnetic tape only one side of the ribbon is used for storing data. It is sequential memory which contains thin plastic ribbon to store data a
2 min read
8085 program to exchange a block of bytes in memory
Problem - Write an assembly level program in 8085 microprocessor to exchange a block of 4 bytes starting from address 2001 with data starting from address 3001. Algorithm - Take a count equal to 4 Store the starting address of both blocks in 2 different register pairs Now exchange the contents at the addresses in both register pairs Increment the v
2 min read
Memory Segmentation in 8086 Microprocessor
Prerequisite - Segmentation Segmentation is the process in which the main memory of the computer is logically divided into different segments and each segment has its own base address. It is basically used to enhance the speed of execution of the computer system, so that the processor is able to fetch and execute the data from the memory easily and
3 min read
Direct memory access with DMA controller 8257/8237
Suppose any device which is connected to input-output port wants to transfer data to memory, first of all it will send input-output port address and control signal, input-output read to input-output port, then it will send memory address and memory write signal to memory where data has to be transferred. In normal input-output technique the process
3 min read
Memory Banking in Microprocessor
The 8086 processor provides a 16-bit data bus. So It is capable of transferring 16 bits in one cycle but each memory location is only of a byte(8 bits), therefore we need two cycles to access 16 bits(8 bit each) from two different memory locations. The solution to this problem is Memory Banking. Through Memory banking, our goal is to access two con
3 min read
Memory Interleaving
Prerequisite - Virtual Memory Abstraction is one of the most important aspects of computing. It is a widely implemented Practice in the Computational field. Memory Interleaving is less or More an Abstraction technique. Though it's a bit different from Abstraction. It is a Technique that divides memory into a number of modules such that Successive w
3 min read