They are in many ways similar to mathematical functions, but can have side-effects outside of the simple "return value" that functions return (result in). Some programming languages make very little syntactic distinction between functions and subroutines.
There are many advantages to breaking a program up into subroutines, including:
The components of a subroutine may include:
Many programming languages, such as Pascal , Fortran, Ada, distinguish between functions or function subprograms, which return values (via a return statement), and subroutines or procedures, which do not. Some languages, such as C and Lisp, do not make this distinction, and treat those terms as synonymous. The name method is commonly used in connection with object-oriented programming, specifically for subroutines that are part of objects; it is also used in conjunction with type classes.
Early FORTRAN compilers were written for machines like the HP 2100 which did not support stacks (or recursion) with hardware stack registers. The Jump to subroutine instruction had the following format:
label JSB m[,I] comments
The address for label is placed into the location represented by m and control transfers to the NEXT location, m+1. On completion of the subroutine, control may be returned to the normal sequence by performing a JMP m,I. This reserves a location at or before the start of a subroutine to save the return location. This did not require a separate stack, but did not support recursion since there is only one return storage location per subroutine. A similar technique was used by Lotus 1-2-3 to support a tree walk to compute recalculation dependencies, as a location was reserved in each cell to store the "return" address. Since circular references are not allowed for natural recalculation order, this allows a tree walk without reserving space for a stack in memory which was very limited on small computers such as the IBM PC.
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 System/360 saved this address in a processor register, relying on convention to save and restore registers and return addresses in memory associated with individual subroutines, then using branches to the address specified in the register to accomplish a subroutine return.
Compilers for most languages use a push-down stack and support recursive subroutine calls (each call is given a fresh new location to store the return address). In a stack based architecture, the return address is 'pushed' as a point of return on the stack. The subroutine 'returns' by 'popping' 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. The disadvantage of such a scheme is that the stack can overflow if recursion takes place at too many levels, or if the variables on each stack frame are too large. If there is not sufficient stack space, and there is no recursion, a tree-walk can be simulated with an iterative algorithm, storing return locations at each tree node, as was done with Lotus 1-2-3 and work-alike clone, The Twin which were based on PC's with very limited stack space.
This section deals with the modern implementation of having subroutine data stored on one or more stacks.
Due to usage of a stack, a subroutine can call itself (see recursion) or other subroutines (nested calls), and of course it can call the same subroutine from several distinct places. Assembly languages generally do not provide programmers with such conveniences as local variables or subroutine parameters. They get to be implemented by passing values in registers or pushing them onto the stack (or another stack, if there is more than one).
When there is just one stack, the return addresses must be placed in the same space as the parameters and local variables. Hence, a typical stack may look like this (for a case where function1 calls function2):
This is with a forwards-growing stack — on many architectures the stack grows backwards in memory. Forward and backwards-growing stacks are useful because it is quite practical to have two stacks growing towards each other in a common scratch space, using one mainly for control information like return addresses and loop counters and the other for data. (This is what Forth does.)
The parts of the program which are responsible for the entry into and exit out of the subroutine (and hence, the setting up and removal of each stack frame) are called the function prologue and epilogue.
If the procedure or function itself uses stack handling commands, outside of the prologue and epilogue, e.g. to store intermediate calculation values, the programmer needs to keep track of the number of 'push' and 'pop' instructions so as not to corrupt the original return address.
In pure functional programming languages such as Haskell, subprograms can have no side effects, and will always return the same result if repeatedly called with the same arguments. Such languages typically only support functions, since subroutines that do not return a value have no use unless they can cause a side effect. In functional programming writing to a file is a side effect.
voidto indicate that a function takes no parameters (especially in C) and/or does not return any value. Note that C/C++ functions can have side-effects, including modifying any variables whose addresses are passed as parameters (i.e. "passed by reference"). Examples:
The function does not return a value and has to be called as a stand-alone function, e.g.,
This function returns a result (the number 5), and the call can be part of an expression, e.g.,
x + function2()
This function converts a number between 0 to 6 into the initial letter of the corresponding day of the week, namely 0 → 'S', 1 → 'M', ..., 6 → 'S'. The result of calling it might be assigned to a variable, e.g.,
num_day = function3(number);.
This function does not return a value but modifies the variable whose address is passed as the parameter; it would be called with "
A subprogram may have any number and nature of call sites. If recursion is supported, a subprogram may even call itself, causing its execution to suspend while another nested execution of the same subprogram occurs. Recursion is a useful technique for simplifying some complex algorithms, and breaking down complex problems. Recursive languages generally provide a new copy of local variables on each call. If the programmer desires the value of local variables to stay the same between calls, they can be declared "static" in some languages, or global values or common areas can be used.
Early languages like Fortran did not initially support recursion because variables were statically allocated, as well as the location for the return address. Most computers before the late 1960s such as the PDP-8 did not have support for hardware stack registers.
Modern languages after ALGOL such as Pl/1 and C almost invariably use a stack, usually supported most modern computer instruction sets to provide a fresh activation record for every execution of a subprogram. That way, the nested execution is free to modify its local variables without concern for the effect on other suspended executions in progress. As nested calls accumulate, a call stack structure is formed, consisting of one activation record for each suspended subprogram. In fact, this stack structure is virtually ubiquitous, and so activation records are commonly referred to as stack frames.
Some languages such as Pascal and Ada also support nested subroutines, which are subroutines callable only within the scope of an outer (parent) subroutine. Inner subroutines have access to the local variables of the outer subroutine which called them. This is accomplished by storing extra context information within the activation record, also known as a display.
If a subprogram can function properly even when called while another execution is already in progress, that subprogram is said to be re-entrant. A recursive subprogram must be re-entrant. Re-entrant subprograms are also useful in multi-threaded situations, since multiple threads can call the same subprogram without fear of interfering with each other.
In a multi-threaded environment, there is generally more than one stack. An environment which fully supports coroutines or lazy evaluation may use data structures other than stacks to store their activation records.
When a series of functions with the same name can accept different parameter profiles or parameters of different types, each of the functions is said to be overloaded.
As another example, a subroutine might construct an object that will accept directions, and trace its path to these points on screen. There are a plethora of parameters that could be passed in to the constructor (colour of the trace, starting x and y co-ordinates, trace speed). If the programmer wanted the constructor to be able to accept only the color parameter, then he could call another constructor that accepts only color, which in turn calls the constructor with all the parameters passing in a set of "default values" for all the other parameters (X and Y would generally be centered on screen or placed at the origin, and the speed would be set to another value of the coder's choosing).
Experienced programmers recommend that a subprogram perform only one task. If a subprogram performs more than one task, it should be split up into more subprograms. They argue that subprograms are key components in maintaining code and their roles in the program must be distinct.
Some advocate that each subprogram should have minimal dependency on other pieces of code. For example, they see the use of global variables as unwise because it adds tight-coupling between subprograms and global variables. If such coupling is not necessary at all, they advise to refactor subprograms to take parameters instead. This practice is controversial because it tends to increase the number of passed parameters to subprograms.
There is a runtime overhead associated with passing parameters, calling the subprogram, and returning. The actual overhead for each invocation depends on the local context at the point of call and the requirements specified in the architecture's application binary interface.
One technique used to minimise this overhead is inline expansion of the subprogram call site. However, inlining often increases code size and can introduce cache misses into a previously optimised block of code.
Dynamic dispatch can introduce further overheads - although the performance difference between indirect and direct calls on commodity CPUs has narrowed since the 1980s, because of research and work done by CPU designers (driven by the increasing popularity of object-oriented programming, which uses dynamic dispatch extensively). Also, software techniques have been developed to make dynamic dispatch more efficient.
y = sqrt(x)) where a subprogram to print out a number might be a "procedure" (eg:
print(x)). This is not a distinction found in all programming languages and notably the C family of programming languages use the two terms interchangeably. See also: Command-Query Separation.
People who write compilers, and people who write in assembly language, deal with the low-level details involved in implementing subroutines:
Most subprograms typically implement the idea of an algorithm -- they are given a finite amount of information when they start, they are given no more information while they run, and they give out no information until they end. However, each process, job, task, or thread is a program or subprogram that typically sends and receives information many times before it ends.
Patent Application Titled "Maintenance of a Subroutine Repository for an Application under Test Based on Subroutine Usage Information" Published Online
Jul 18, 2013; By a News Reporter-Staff News Editor at Computer Weekly News -- According to news reporting originating from Washington, D.C., by...
Researchers Submit Patent Application, "Maintenance of a Subroutine Repository for an Application under Test Based on Subroutine Usage Information", for Approval
Jul 18, 2013; By a News Reporter-Staff News Editor at Computer Weekly News -- From Washington, D.C., VerticalNews journalists report that a...
Researchers Submit Patent Application, "Automatic Identification of Subroutines from Test Scripts", for Approval
Jan 03, 2013; By a News Reporter-Staff News Editor at Politics & Government Week -- From Washington, D.C., VerticalNews journalists report that...