A subroutine is a unit of program code that can be invoked to perform a particular task, usually with supplied inputs, and normally returns control to the point following its invocation. Subroutines are a fundamental abstraction in programming languages: they allow an operation to be defined once and used from multiple places, while separating its interface from its implementation. Depending on the language and context, subroutines may be called functions, procedures, methods, or simply routines.
Purpose and terminology
A subroutine groups an operation behind a callable interface. Instead of repeating the instructions for that operation, a program makes a call that transfers control to the subroutine. The calling code is the caller; the invoked subroutine is the callee.
Subroutines support several related purposes:
- Decomposition: dividing a large program into smaller, comprehensible operations.
- Reuse: sharing an implementation among multiple callers.
- Abstraction: allowing callers to use an operation without depending on its internal instructions.
- Independent testing and maintenance: providing boundaries at which behavior can be checked or changed.
The terminology varies between languages. A function commonly returns a value, while a procedure commonly performs an action without returning a value directly. This distinction is not universal: C, for example, calls both value-returning routines and routines with a void return type functions. In object-oriented programming, a method is a subroutine associated with a class or object; instance methods generally have access to a particular receiver object.
A programming function is not necessarily a mathematical function. It may depend on mutable state, produce output, alter data, or return different results on successive calls with the same explicit arguments. A pure function, by contrast, produces its result without observable side effects and depends only on its inputs.
Definition, invocation, and return
A subroutine definition generally specifies a name or another means of identification, formal parameters, a body, and—where applicable—a result type. A call supplies arguments corresponding to those parameters.
For example, in pseudocode:
function maximum(a, b):
if a > b:
return a
return b
largest = maximum(12, 7)
Here, a and b are formal parameters: names used inside the definition. The values 12 and 7 are arguments supplied by the call. The returned value is assigned to largest.
A subroutine's signature describes interface information such as its name, parameter types, and result type, although the exact meaning of “signature” differs between languages. A type system may check that calls provide suitable arguments and use results consistently.
In an ordinary synchronous call, the caller waits while the callee executes, and execution resumes when the callee returns. A return may supply a value, several values, or no value. Not every invocation returns normally: it may terminate by raising an exception, ending the process, transferring control elsewhere, or continuing indefinitely.
Calling a subroutine is distinct from an unrestricted jump in control flow. A call establishes an expectation of returning to a particular continuation—the computation that should proceed after the call—even if a particular execution never reaches it.
Parameters, results, and state
Languages provide different rules for passing arguments. These rules determine what the callee receives and which changes can be observed by the caller.
- Pass by value: the callee receives a value used to initialize a parameter. Assigning a new value to that parameter does not, by itself, reassign the caller's variable.
- Pass by reference: a parameter provides access to the caller's storage location, so assignments through the parameter can change the caller's variable.
- Call by sharing: the caller and callee can refer to the same object. Mutating that object can be visible to both, while rebinding the parameter does not rebind the caller's variable.
These descriptions must be interpreted in the context of a language's semantics. Passing a pointer by value, for example, copies the pointer value, not the object it points to. The callee may therefore modify that object without having received the pointer variable itself by reference.
When multiple parameters or other references designate the same storage, aliasing occurs. This can complicate reasoning about updates and constrain compiler optimizations.
A subroutine may also access information not supplied as an explicit argument, including global variables, object fields, or variables from an enclosing scope. A function packaged together with access to its surrounding lexical environment is called a closure. Such environments can outlive the invocation that originally created them.
Observable effects beyond producing a return value are called side effects. Examples include changing shared data, writing a file, or sending a network message. The treatment of side effects is particularly important in functional programming, where pure computations are often distinguished from effectful operations.
Runtime implementation
A language's subroutine semantics do not require one particular machine implementation. Nevertheless, many implementations use a call stack, typically organized as a stack of activation records, also called stack frames.
An activation record may contain:
- the return address;
- arguments or space for outgoing arguments;
- local variables and temporary values;
- saved processor registers;
- information used for exception handling or access to enclosing scopes.
Each active invocation can have its own record. This separates the local state of nested calls and permits multiple simultaneous invocations of the same routine.
At the level of machine code, a call may use instructions that record a return address and transfer execution to the callee. Some architectures place the return address in a register; others commonly place it on a stack. A compiler, interpreter, or virtual machine implements the details appropriate to its execution model.
A calling convention specifies details such as where arguments and results are placed, which registers a callee must preserve, and who adjusts stack storage. Calling conventions form part of an application binary interface, enabling separately compiled components to call one another correctly.
The source-level existence of a subroutine does not imply that execution must create a physical stack frame. A compiler may eliminate a call, keep values in registers, allocate an environment elsewhere, or transform the control flow while preserving the program's required behavior.
Recursion and related forms
A subroutine is recursive if it calls itself directly or participates in a cycle of calls. Recursion is useful for expressing operations on nested structures, such as traversing a tree, and for implementing divide-and-conquer algorithms.
Each active recursive invocation normally has distinct parameters and local state. Excessive recursion can exhaust available stack space. A tail call occurs when returning the callee's result is the caller's final action. Implementations that support tail-call elimination can perform suitable calls without retaining an additional active stack frame.
Subroutines also appear in several more specialized forms:
- First-class functions: callable values that can be stored, passed as arguments, and returned as results.
- Higher-order functions: routines that accept callable values or return them.
- Callbacks: routines supplied to another component for invocation when an event occurs or an operation reaches a particular stage.
- Methods: routines associated with classes or objects, sometimes selected at runtime according to the receiver's type.
A coroutine extends the ordinary call-and-return pattern by allowing execution to suspend and later resume with its local state preserved. In asynchronous programming, calling an asynchronous function may produce a task, future, or promise before the underlying operation completes. The exact relationship between invocation, execution, suspension, and completion depends on the language and runtime.
Historical development
Subroutines developed alongside early stored-program computers as a way to reuse instruction sequences and organize programs. Early implementations had to solve the problem of returning from a shared routine to different calling locations, sometimes using techniques that modified instructions or return-address storage.
The EDSAC programming environment became an influential early example of reusable subroutine libraries. The Preparation of Programs for an Electronic Digital Computer, published in 1951 by Maurice Wilkes, David Wheeler, and Stanley Gill, described programming methods centered on such reusable routines.
Higher-level languages made subroutines explicit language constructs rather than merely machine-level conventions. Fortran distinguished functions and subroutines, while later languages developed richer facilities for nested procedures, recursion, callable values, and object-associated methods. These developments expanded the expressive role of subroutines beyond sharing repeated instruction sequences.
Applications and limitations
Subroutines are a basic unit of organization in software engineering. Libraries expose callable operations, and an application programming interface often specifies the parameters, results, errors, and behavioral obligations of those operations. Implementations may change behind that interface, provided they preserve the promised behavior.
A call has potential costs: transferring control, passing arguments, preserving registers, allocating activation storage, and returning results. Inlining replaces a call with code derived from the callee's body, potentially removing call overhead and enabling further optimization. It can also increase program size and pressure on instruction caches. The balance depends on the workload and implementation.
Subroutine boundaries do not automatically guarantee good modularity. A routine that relies heavily on global state may be difficult to understand in isolation. Excessively small routines can fragment a computation, while overly large routines can combine unrelated responsibilities.
Concurrent execution introduces additional concerns. A routine is reentrant when it can be entered again before an earlier invocation has completed without corrupting its operation. Reentrancy is not identical to thread safety: a routine may protect shared state with locks and still be unsafe to reenter in some contexts. In concurrent computing, unsynchronized access to mutable shared state can produce a race condition regardless of how the source code is divided into routines.
Subroutine boundaries also support formal verification through contracts such as preconditions and postconditions. These specify what must hold before a call and what the routine guarantees on completion. Establishing those guarantees still requires accounting for termination, exceptional exits, aliasing, and changes to shared state.