Wednesday, 22 May 2013

Subroutines

It is a set of program instructions that are designed to perform a specific task and are written separately and stored in memory.Subroutines can be defined within programs, or separately in libraries that can be used by multiple programs.
It is totally different from functions in the manner that function takes parameters, perform works and does not alter any value or work with any value outside it's scope .Functions also returns some value ,although their are some function in C that do not return any value like Void() . Subroutine directly work with the values of the caller/the code segment which invoked it, and does not return values.

Explanation: Consider the example of a program in which you have to perform multiplication repeatedly and you have to write the same code again and again.to avoid so you can use a Subroutine that can be called repeatedly.Subroutines are called by CALL function.The last Instruction of every subroutine is RET to return to main program.Program may have more than one subroutines.
When Program execution is jumped from main program to subroutine, the contents of Program Counter (PC) are saved to stack .The main motive of doing so is that program execution can return to proper point of main program.



Advantages of Subroutines
1)Reduces duplicate code within the program.
2)Decomposes complex program into simple.
3) Same code can be used into multiple programs.

Figure given below clearly illustrates subroutines.

No comments:

Post a Comment