Microsoft Store
 

Subroutine


 

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", thus allowing programs to access the subroutine repeatedly without the subroutine's code having been written more than once. In many programming languages the word function is reserved for subroutines that return a value; however, the C programming language and its programmers view subroutines simply as functions that do not return a value.

Technical overview

A subprogram, as its name suggests, 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 values. Generally, subprograms execute their statements from top to bottom.

Related Topics:
Return - Parameter

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

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; that is, a subprogram that returns a random number each time it is called.

Related Topics:
Imperative programming languages - Side-effects - Pseudorandom number generator

~ ~ ~ ~ ~ ~ ~ ~ ~ ~

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.)

~ ~ ~ ~ ~ ~ ~ ~ ~ ~