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

Subroutine, Subroutine nesting and Stack memory

Last Updated : 29 Aug, 2023
Summarize
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 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
Difference between Uniform Memory Access (UMA) and Non-uniform Memory Access (NUMA)
In computer architecture, and especially in Multiprocessors systems, memory access models play a critical role that determines performance, scalability, and generally, efficiency of the system. The two shared-memory models most frequently used are UMA and NUMA. This paper deals with these shared-memory models, explaining their characteristics, adva
5 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
9 min read
Difference between Virtual memory and Cache memory
Virtual Memory and Cache Memory are important substructures of contemporary computing systems that perform an important function in terms of enhancing capabilities. But they are dissimilar in terms of functionality and function differently. Virtual memory works as extra physical memory of the system and Cache memory provides quick access to frequen
5 min read
Difference between Random Access Memory (RAM) and Content Addressable Memory (CAM)
In the world of computation, memory plays a very significant role in ensuring efficient data processing and data storage or data retrieval. Memory system are the very crucial part of any particular digital devices , it facilitate to store and retrieve the Data from the devices . Two important types of memory are Random Access Memory ( RAM ) and Con
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
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
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 Efficiency and Speedup in Cache Memory
To understand the operation of cache memory, one has to familiarize the concepts of efficiency as well as speedup in computer architecture. These two metrics are sometimes considered synonyms but in fact they have different applications and let a system analyst come across different picture of the system’s efficiency. Effectiveness is the ability o
6 min read
Difference between Cache Memory and Register
In the context of a computer’s architecture, two terms that may be familiar are the cache memory and the register, however, few people may not know the differences and functions of each of the two components. Both of them are important to the CPU but they have different roles and are used in different manner. In this article, we will look at some i
5 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). The data on which CPU needs to work out is stored temporarily in RAM. The disadvantage of RAM is, it's volatile and data is lost once the computer is turned off or shut down at failure. On the other hand, HDD is not volatile and used to
6 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
5 min read
Locality of Reference and Cache Operation in Cache Memory
This article deals with the concept of locality of reference and cache operations in cache memory. Locality of reference refers to the process of accessing a particular portion of memory at any given time period. Cache memory is a small-sized memory that allows fast access by storing the frequently needed data and instructions. And cache operations
7 min read
Difference between Simultaneous and Hierarchical Access Memory Organisations
In the Computer System Design, memory organization is important in order to enhance system performance and efficiency . So, two ways have been devised on the basis of which CPU tries to access different levels of Memory. These two types include Simultaneous Access Memory Organization and Hierarchical Access Memory Organization . Let's explore these
5 min read
Difference between Memory Mapped IO and IO Mapped IO with reference to 8085 microprocessor
In the field of microprocessor architectures, Input/Output (I/O) operations are primitive for communicating with peripheral equipment. The 8085 microprocessor employs two primary methods for handling I/O operations: Memory Mapped I/O Versus I/O Mapped I/O. It is essential to become familiar with the distinctions existing between these two types of
7 min read
Advantages and Disadvantages of Flash Memory
Flash memory is digital storage technology that retains the data stored in the memory even when the electrical power is turned off. It is used in; USB drive, memory cards, smart phones, SSDs among others. The benefits and drawbacks of using flash memory will be discussed in this article to give the reader a better understanding of why this particul
9 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
6 min read
Differences between Associative and Cache Memory
Memory system is the only subsystem of computer architecture that contributes a lot to the speed and efficiency of result processing. Among different types of memory that can be mentioned in discussions, associative and cache memories play crucial roles. Because associative memory is also called content-addressable memory (CAM), it retrieves data b
5 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]m
3 min read
Difference Between Register and Memory
Registers and memory are essential for the operation of a computer, each having its own advantages. Registers offer the CPU quick access to data it must process, thus ensuring fast operation. Memory, on the other hand, provides storage space needed for large amounts of data and instructions during program execution. Although registers are small and
5 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