You are on page 1of 6

Subroutine

Subroutine
• Written and stored
• The block of instruction which carries out a
specific and well defined task is called subroutine
• Halt the main program
• Provide returning to the same
• Transfer control to subroutine
• Execute the subroutine
• Revert to the main routine
Subroutine
• A subprogram that can be used any number of times
by the main program
• When the same function is required more than once
in a program, it is frequently written as a subroutine
• Subroutines allow a program to break down a
complex task into smaller, more manageable pieces.
• A subroutine is a block of code that can be called
from anywhere in the program, and then returns
control back to the calling code when it is done.
Subroutine
• CALL 16-bit address
• This instruction is used to call a subroutine.
• The current program counter(PC) is pushed
onto the stack, and then the program counter
is set to the address of the first instruction in
the subroutine
Subroutine
• RET:
• This instruction is used to return from a
subroutine.
• The topmost item on the stack is popped into
the program counter, which restores the
original program counter and countinues
execution of the calling code.
Subroutine
• Note that the stack state in the figure
corresponds to the time at which the
processor executes instructions within the
second subroutine.
• Also note that if the stack is used for register
savings in a subroutine, the recovery should be
done in the reverse order and in a balanced
fashion, otherwise the return address cannot
be recovered properly into the PC.

You might also like