Open In App

How is return address specified in Stack?

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Stack:

A stack is a linear data structure in which elements are accessed with one end called the “top” of the stack. It follows the LIFO (Last In First Out) approach.

Program Counter:

The program counter is a special purpose register in the CPU which stores the memory location of the next instruction.

Note: The article uses the abbreviated form “PC” in place of Program Counter.

Stack Pointer:

A stack pointer is a special register in the CPU which is used to store the address of the top element of the stack.

When and how the return address is specified in the Stack?

  • The return address is specified in the stack when a program contains a function call or subroutine.
  • When the function is called then, after its complete execution it has to return back to the original program i.e., the next instruction after the function call in the program.
  • When the function call is to be executed then, the program counter PC holds the address of the next instruction after the function call in the program.
  • For executing the function, the control has to go to the function definition and after executing the function it has to return to the next instruction after the function call in the program.
  • So, when the function is to be executed then, the PC value i.e., the next instruction address is stored onto the stack (SP incremented) and the PC is updated by the address where the function is stored.
  • After the complete execution of the function, the PC gets updated by the return address present in the stack (value at the top of the stack).

Example:

Assume I3 is the function call instruction and CPU is currently executing I3 and PC = 304

  • The PC value 304 is stored onto the stack and stack pointer SP is incremented by one. 
  • The PC value is updated by 400 i.e., the address where the function is stored. 
  • After complete execution of the function PC value is again updated by stack value (top of stack) and stack pointer SP is decremented by 1.

Follow the below image for a better idea

Example showing storing of return address

Example showing storing of return address


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads