Overview

A subroutine is a self-contained sequence of program instructions that performs a specific task and can be invoked from multiple places in a program. Subroutines are known by several names—procedure, routine, function, or method depending on context and language—and they are a primary mechanism for organizing code, promoting reuse, and reducing repetition. For a general description of programming concepts see programming overview.

Characteristics and components

Typical subroutines have a name, an entry point, an optional parameter list, local storage for variables, and an exit point. When a subroutine is called execution jumps to its entry, runs the body, and then returns control to the caller. Many subroutines can also return a value or multiple values. Common elements include:

  • Name and signature: identifies the routine and its expected inputs.
  • Parameters: values or references passed into the routine; see parameter concepts for more detail.
  • Local variables: storage that exists only during the routine's execution.
  • Return mechanism: a value or status that is given back, or simply a transfer of control.

History and implementation

Subroutines appear in early assembly languages and were formalized as high-level languages developed. Call and return instructions in machine code, and later stack-based calling conventions implemented parameter passing and local storage. Compilers, linkers and runtime systems manage how subroutines are organized into libraries and how addresses are resolved at compile or run time. For historical and technical resources, consult programming history.

Uses, examples and importance

Subroutines are used to break programs into manageable pieces: input/output handling, mathematical computations, data processing, or user-defined utilities. Examples include a routine that sorts an array, computes a checksum, or validates input. Benefits include:

  • Modularity—easier to read, test, and maintain code.
  • Code reuse—avoid duplication by calling the same logic from many places.
  • Abstraction—hide implementation details behind a clear interface.

Libraries of subroutines form the basis of reusable software components; many language standard libraries expose hundreds of such routines. See library and API examples for typical collections.

Distinctions and notable facts

Different terms reflect subtle differences: a function usually denotes a subroutine that returns a value, a procedure may not return one, and a method is attached to a data type or object in object-oriented languages. Macros differ by being expanded at compile time rather than invoked at run time. Recursion is possible when a subroutine calls itself, and performance trade-offs (call overhead, inlining) influence implementation choices.

Understanding subroutines is essential for writing clear, maintainable software and for leveraging libraries and frameworks across programming paradigms.