Microsoft Store
 

Subroutine


 

In computer science, a subroutine (function, procedure, or subprogram) is a sequence of code which performs a specific task, as part of a larger program, and is grouped as one or more statement blocks; such code is sometimes collected into software libraries. Subroutines can be "called", thus allowing programs to access the subroutine repeatedly without the subroutine's code having been written more than once. In many programming languages the word function is reserved for subroutines that return a value; however, the C programming language and its programmers view subroutines simply as functions that do not return a value.

History

The first use of subprograms was in assembly languages that did not have a call instruction. On these computers, subroutines needed to be called by a sequence of lower level instructions, possibly implemented as a macro. These instructions typically modified the program code rather like the infamous Cobol alter statement, modifying the address of a branch at a standard location so that it behaved like an explicit return instruction. Even with this cumbersome approach subroutines proved so useful that soon most architectures provided instructions to help with subroutine calls, clear up to explicit call instructions.

Related Topics:
Assembly language - Cobol - Statement

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

When an assembly language program executes a call, program flow jumps to another location, but the address of the next instruction (that is, the instruction that follows the call instruction in memory) is kept somewhere to use when returning. The IBM 360 range used to save this address in a processor register, relying on macros to save and restore deeper return addresses in memory associated with individual subroutines, then using branches to the address specified in the register to accomplish a subroutine return. However stacks have proved to be a better approach, since they automatically cater for recursive subroutine calls, and were typically used in all but a few later architectures. In a stack based architecture, the return address is 'pushed' as a point of return on the stack. The subroutine exits by 'pop'ing a return value from the top of the stack, which reads the previously pushed return address and jumps to it, so that program flow continues immediately after the call instruction. Most RISC and VLIW architectures save the return address in a link register (as the IBM 360 did), but simulate a stack with load and store instructions rather than with push and pop instructions.

Related Topics:
Processor register - Return - Stacks - Recursive - Link register

~ ~ ~ ~ ~ ~ ~ ~ ~ ~