A subroutine is a sequence of computer instructions that is contained in a larger program, typically used to perform a particular task and is referred to by name. They are also known as subprograms, procedures, functions, methods, subprocesses, routines or segments.
Subroutines are used to increase code readability and reusability by allowing the same functionality to be accessed multiple times from different points in the program. This is achieved by means of a subroutine’s ability to be called from any other program, performing the same operation or calculations.
Subroutines are often written in a high-level programming language such as C or Java, however assembly language is also used for writing subroutines. Sometimes, subroutines are written by the programmer and stored in a library, while other times they already exist in the operating system.
When a subroutine is called, the control flow is transferred to it, where it begins by saving the state of the program, so it can return to the point at which it was called. Then, the instructions of the subroutine are executed in order and, when finished, it returns control flow to the main program.
Along with providing code reusability, they can be beneficial when it comes to making changes. If a new version of the subroutine is created, it can be called instead of the main program needing to be modified. This helps to reduce the overhead of making substantial changes and makes it easier to debug the code.
Subroutines are one of the most fundamental components of computer programming, as they allow code to be broken down into small, reusable pieces. They are today an essential part of most programming languages, and for good reason – without them, most programs would take far more time and effort to create and manipulate.