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", this allows programs to access the subroutine repeatedly, without the subroutine's code having been written more than once.

Table of contents
1 History
2 Technical Overview
3 C/C++ Examples
4 Ruby Example
5 Why use subprograms?
6 Local variables, recursion, and re-entrancy
7 Conventions
8 Related terms and clarification

History

The first use of subprograms was in assembly languages.

Technical Overview

A subprogram, as its name suggest, somehow behaves like a computer program. Typically, the caller waits for subprograms to finish and continues execution only after a subprogram "returns". Subroutines are often given parameters to refine their behavior or to perform a certain computation with given (variable) values. Generally, subprograms execute their statements from top to bottom.

In most imperative programming languages, subprograms may have so-called side-effects, that is, they may cause changes that remain after the subprogram has returned. Usually, compilers cannot predict whether a subprogram has a side-effect or not, but can determine if a subprogram calls no other subprograms, or at least no other subprograms that have side-effects. In imperative programming, compilers usually assume every subprogram has a side-effect to avoid complex analysis of execution paths. Because of its side-effects, a subprogram may return different results each time it is called, even if it is called with the same arguments. A simple example is a subprogram that implements a Pseudorandom number generator, i.e. a subprogram that returns a random number each time it is called . Such behavior is invalid in a strict mathematical sense. An exception to this common behaviour is found in functional programming languages, where subprograms can have no side effects, and will always return the same result if repeatedly called with the same arguments. [Note that subprograms are referred to as functions in these languages].

C/C++ Examples

In the C and C++ programming languages, subprograms are referred to as "functions". Below are three such functions - the first function does absolutely nothing; it is called with: "function1();. The second function returns the number 5; the function can be called with: "function2();" The third function returns a desired selection (1-5), and is called with: "function2(number);"

void function1()
{
}

int function2()
{
 return 5;
}

 
int function3(int number)
{
 int selection[] = {5,1,3,2,4};
 return selection[number];
}

Ruby Example

The following is an example of a Ruby subprogram, which outputs "text".

def say_text
 print "text\\n"
end

say_text

Why use subprograms?

There are numerous motivations for the use of subprograms:

Generally, to make use of a subprogram, a programmer places some form of call instruction--which constitutes a call site--into an instruction sequence. When the call site is encountered, the instruction sequence is temporarily suspended, and the subprogram itself executes until it completes, at which time the original instruction sequence resumes.

Local variables, recursion, and re-entrancy

A subprogram may find it useful to make use of a certain amount of "scratch" space; that is, memory used during the execution of that subprogram to hold intermediate results. Variables stored in this scratch space are referred to as local variables, and the scratch space itself is referred to as an activation record. An activation record typically has a return address that tells it where to pass control back to when the subprogram finishes.

A subprogram may have any number and nature of call sites; in fact, a subprogram may even call itself, causing its execution to suspend while another nested execution of the same subprogram occurs. This is referred to as recursion, and is a useful technique for making some complex algorithms more comprehensible. However, recursion poses a problem if the recursive execution modifies any local variables, because when the suspended execution resumes, it will find that the data stored in its local variables have been lost.

Early languages like Fortran simply didn't support recursion for this reason. Modern languages almost invariably 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.

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.

Conventions

A number of conventions of coding subprogram have been developed. It has been commonly preferable that the name of subprogram is a verb when it does certain task and is adjective when it does some inquring and is a noun when it is used to substitute variables and such.

The 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 role in the program must be distinct.

Some advocate that each subprogram should have least dependecy to other parts of code. For example, they see the use of global variables evil because it adds tight-coupling between subprograms and global variables, if such coupling is not unnecessary at all and advise to refactor subprogram to take parameters instead. This practice is controversial because it tends to increase the number of passed parameters to subprograms.

See programming practice for more details discussion of programming disciplines.

Related terms and clarification

Different programming languages and methodologies possess notions and mechanisms related to subprograms: