---
title: Function (computer programming)
slug: function-computer-programming
qid: 
snapshot: enwiki-001377715877
content_hash: 
license: CC BY-SA 4.0
source: https://en.wikipedia.org/w/index.php?oldid=1377715877
tags: [112947818, 20416984, 22900667, 22921557, 22922140, 22936277, 22959301, 23118434, 23603337, 23837581, 24043274, 24745122, 28043570, 30459724, 62213919, 70721507, 81199107, 99425588]
---

# Function (computer programming)

> [!note] Provenance
> Snapshot `enwiki-001377715877` · content root `…`
> Derived from <https://en.wikipedia.org/w/index.php?oldid=1377715877> · Licensed CC BY-SA 4.0

In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-formed interface and behavior and can be invoked multiple times. Callable units provide a powerful programming tool. The primary purpose is to enable the decomposition of a large and/or complicated problem into chunks that have relatively low cognitive load. These smaller, less complicated chunks (callable units) can become conceptually independent of the larger problem, taking on meaningful names of their own and potentially becoming useful to other unrelated problems through reusability. Judicious application can reduce the cost of developing and maintaining software through modularity and reusability, while increasing quality and reliability. Callable units are present at multiple levels of abstraction in the programming environment. For example, a programmer may write a function in source code that is compiled to machine code that implements similar semantics. There is a callable unit in the source code and an associated one in the machine code, but they are different kinds of callable units—with different implications and features.

In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-formed interface and behavior and can be invoked multiple times. Callable units provide a powerful programming tool. The primary purpose is to enable the decomposition of a large and/or complicated problem into chunks that have relatively low cognitive load. These smaller, less complicated chunks (callable units) can become conceptually independent of the larger problem, taking on meaningful names of their own and potentially becoming useful to other unrelated problems through reusability. Judicious application can reduce the cost of developing and maintaining software through modularity and reusability, while increasing quality and reliability. Callable units are present at multiple levels of abstraction in the programming environment. For example, a programmer may write a function in source code that is compiled to machine code that implements similar semantics. There is a callable unit in the source code and an associated one in the machine code, but they are different kinds of callable units—with different implications and features. ==Terminology== Some programming languages, such as COBOL and BASIC, make a distinction between functions that return a value (typically called "functions") and those that do not (typically called "subprogram", "subroutine", or "procedure"); some, such as C, C++, and Rust, only use the term "function" irrespective of whether they return a value or not; others, such as ALGOL 60 and PL/I, only use the word procedure. Some object-oriented languages, such as Java and C#, refer to functions inside classes as "methods". ==History== The idea of a callable unit was initially conceived by John Mauchly and Kathleen Antonelli during their work on ENIAC and recorded in a January 1947 Harvard symposium on "Preparation of Problems for EDVAC-type Machines." Maurice Wilkes, David Wheeler, and Stanley Gill are generally credited with the formal invention of this concept, which they termed a closed sub-routine, contrasted with an open subroutine or macro. However, Alan Turing had discussed subroutines in a paper of 1945 on design proposals for the NPL ACE, going so far as to invent the concept of a return address stack. The idea of a subroutine was worked out after computing machines had already existed for some time. The arithmetic and conditional jump instructions were planned ahead of time and have changed relatively little, but the special instructions used for procedure calls have changed greatly over the years. The earliest computers, such as the Manchester Baby, and some early microprocessors, such as the RCA 1802, did not have a single subroutine call instruction. Subroutines could be implemented, but they required programmers to use the call sequence—a series of instructions—at each call site. A single subroutine was implemented in 1945 in Konrad Zuse's Z4 in the form of a tape. In 1945, Alan Turing used the terms "bury" and "unbury" as a means of calling and returning from subroutines. In January 1947 John Mauchly presented general notes at A Symposium of Large Scale Digital Calculating Machinery under the joint sponsorship of Harvard University and the Bureau of Ordnance, United States Navy. Here he discusses serial and parallel operation suggesting: Kay McNulty had worked closely with John Mauchly on the ENIAC team and developed an idea for subroutines for the ENIAC computer she was programming during World War II. She and the other ENIAC programmers used the subroutines to help calculate missile trajectories. Goldstine and von Neumann wrote a paper dated 16 August 1948 discussing the use of subroutines. Some very early computers and microprocessors, such as the IBM 1620, the Intel 4004 and Intel 8008, and PIC microcontrollers, have a single-instruction subroutine call that uses a dedicated hardware stack to store return addresses; such hardware supports only a few levels of subroutine nesting, but can support recursive subroutines. Machines before the mid-1960s, such as the UNIVAC I, the PDP-1, and the IBM 1130, typically use a calling convention which saved the instruction counter in the first memory location of the called subroutine. This allows arbitrarily deep levels of subroutine nesting but does not support recursive subroutines. The IBM System/360 had a subroutine call instruction that placed the saved instruction counter value into a general-purpose register; with additional code, this can be used to support arbitrarily deep subroutine nesting and recursive subroutines. The Burroughs B5000 (1961) is one of the first computers to store subroutine return data on a stack. The DEC PDP-6 (1964) is one of the first accumulator-based machines to have a subroutine call instruction that saved the return address in a stack addressed by an accumulator or index register. The later PDP-10 (1966), PDP-11 (1970) and VAX-11 (1976) lines followed suit; this feature also supports both arbitrarily deep subroutine nesting and recursive subroutines. ===Language support=== In the very early assemblers, subroutine support was limited. Subroutines were not explicitly separated from each other or from the main program, and indeed the source code of a subroutine could be interspersed with that of other subprograms. Some assemblers would offer predefined macros to generate the call and return sequences. By the 1960s, assemblers usually had much more sophisticated support for both inline and separately assembled subroutines that could be linked together. One of the first programming languages to support user-written subroutines and functions was FORTRAN II. The IBM FORTRAN II compiler was released in 1958. ALGOL 58 and other early programming languages also supported procedural programming. ===Libraries=== Even with this cumbersome approach, subroutines proved very useful. They allowed the use of the same code in many different programs. Memory was a very scarce resource on early computers, and subroutines allowed significant savings in the size of programs. Many early computers loaded the program instructions into memory from a punched paper tape. Each subroutine could then be provided by a separate piece of tape, loaded or spliced before or after the main program (or "mainline" ); and the same subroutine tape could then be used by many different programs. A similar approach was used in computers that loaded program instructions from punched cards. The name subroutine library originally meant a library, in the literal sense, which kept indexed collections of tapes or decks of cards for collective use. ===Return by indirect jump=== To remove the need for self-modifying code, computer designers eventually provided an indirect jump instruction, whose operand, instead of being the return address itself, was the location of a variable or processor register containing the return address. On those computers, instead of modifying the function's return jump, the calling program would store the return address in a variable so that when the function completed, it would execute an indirect jump that would direct execution to the location given by the predefined variable. ===Jump to subroutine=== Another advance was the jump to subroutine instruction, which combined the saving of the return address with the calling jump, thereby minimizing overhead significantly. At least five forms of this existed in the 1950s. Return jump: store the return address in the first word of the subroutine. Return Jump (RJ) on the UNIVAC 1103A is an early example. Index jump: store the return address in an index register. Transfer and Set indeX (TSX) on the IBM 704 is an early example. Automatic storage into a dedicated storage location: the Store P (STP) location on the RCA 501 is an early example. Automatic storage into a designated register: The sequence and cosequence history registers (SH and CSH) on the Honeywell 800 is an early example. Patch return address: The "return address" instruction adds one to the contents of the program counter register and patches the address portion of a branch instruction at the last word of the subroutine with the caller's return address. The "return address" instruction is followed immediately with a branch instruction to the beginning of the subroutine. The LGP-30 is an example. The IBM System/360 architecture is an example of saving the return address into a designated register. The branch instructions BAL or BALR, designed for procedure calling, would save the return address in a processor register specified in the instruction, by convention register 14. To return, the subroutine had only to execute an indirect branch instruction (BR) through that register. If the subroutine needed that register for some other purpose (such as calling another subroutine), it would save the register's contents to a private memory location or a register stack. The HP 2100 architecture is an example of saving the return address in the first word of the subroutine. The JSB instruction would save the return address in the memory location that was the target of the branch. Execution of the procedure would begin at the next memory location. In the HP 2100 assembly language, one would write, for example ... JSB MYSUB (Calls subroutine MYSUB.) BB ... (Will return here after MYSUB is done.) to call a subroutine called MYSUB from the main program. The subroutine would be coded as MYSUB NOP (Storage for MYSUB's return address.) AA ... (Start of MYSUB's body.) ... JMP MYSUB,I (Returns to the calling program.) The JSB instruction placed the address of the NEXT instruction (namely, BB) into the location specified as its operand (namely, MYSUB), and then branched to the NEXT location after that (namely, AA = MYSUB + 1). The subroutine could then return to the main program by executing the indirect jump JMP MYSUB, I which branched to the location stored at location MYSUB. Compilers for Fortran and other languages could easily make use of these instructions when available. This approach supported multiple levels of calls; however, since the return address, parameters, and return values of a subroutine were assigned fixed memory locations, it did not allow for recursive calls. Incidentally, a similar method was used by Lotus 1-2-3, in the early 1980s, to discover the recalculation dependencies in a spreadsheet. Namely, a location was reserved in each cell to store the return address. Since circular references are not allowed for natural recalculation order, this allows a tree walk without reserving space for a stack in memory, which was very limited on small computers such as the IBM PC. ===Call stack=== Most modern implementations of a function call use a call stack, a special case of the stack data structure, to implement function calls and returns. Each procedure call creates a new entry, called a stack frame, at the top of the stack; when the procedure returns, its stack frame is deleted from the stack, and its space may be used for other procedure calls. Each stack frame contains the private data of the corresponding call, which typically includes the procedure's parameters and internal variables, and the return address. The call sequence can be implemented by a sequence of ordinary instructions (an approach still used in reduced instruction set computing (RISC) and very long instruction word (VLIW) architectures), but many traditional machines designed since the late 1960s have included special instructions for that purpose. The call stack is usually implemented as a contiguous area of memory. It is an arbitrary design choice whether the bottom of the stack is the lowest or highest address within this area, so that the stack may grow forwards or backwards in memory; however, many architectures chose the latter. Some designs, notably some Forth implementations, used two separate stacks, one mainly for control information (like return addresses and loop counters) and the other for data. The former was, or worked like, a call stack and was only indirectly accessible to the programmer through other language constructs while the latter was more directly accessible. When stack-based procedure calls were first introduced, an important motivation was to save precious memory. With this scheme, the compiler does not have to reserve separate space in memory for the private data (parameters, return address, and local variables) of each procedure. At any moment, the stack contains only the private data of the calls that are currently active (namely, which have been called but haven't returned yet). Because of the ways in which programs were usually assembled from libraries, it was (and still is) not uncommon to find programs that include thousands of functions, of which only a handful are active at any given moment. For such programs, the call stack mechanism could save significant amounts of memory. Indeed, the call stack mechanism can be viewed as the earliest and simplest method for automatic memory management. However, another advantage of the call stack method is that it allows recursive function calls, since each nested call to the same procedure gets a separate instance of its private data. In a multi-threaded environment, there is generally more than one stack. An environment that fully supports coroutines or lazy evaluation may use data structures other than stacks to store their activation records. If declared to return a value, a call can be embedded in an expression in order to consume the return value. For example, a square root callable unit might be called like y = sqrt(x) . A callable unit that does not return a value is called as a stand-alone statement like print("hello") . This syntax can also be used for a callable unit that returns a value, but the return value will be ignored. Some older languages require a keyword for calls that do not consume a return value, like CALL print("hello") . int fibonacci(unsigned int n) { if (n Early languages like Fortran did not initially support recursion because only one set of variables and return address were allocated for each callable. Early computer instruction sets made storing return addresses and variables on a stack difficult. Machines with index registers or general-purpose registers, e.g., CDC 6000 series, PDP-6, GE 635, System/360, UNIVAC 1100 series, could use one of those registers as a stack pointer. A simple example in Pascal: function E(x: real): real; function F(y: real): real; begin F := x + y end; begin E := F(3) + F(4) end; The function F is nested within E . Note that E 's parameter x is also visible in F (as F is a part of E ) while both x and y are invisible outside E and F respectively. // returns the area of a rectangle defined by height and width double area(double height, double width) { return h * w; } // returns the area of a circle defined by radius double area(double radius) { return radius * radius * std::numbers::pi; } int main() { double rectangleArea = area(3, 4); double circleArea = area(5); } PL/I has the GENERIC attribute to define a generic name for a set of entry references called with different types of arguments. Example: DECLARE gen_name GENERIC( name WHEN(FIXED BINARY), flame WHEN(FLOAT), pathname OTHERWISE); Multiple argument definitions may be specified for each entry. A call to "gen_name" will result in a call to "name" when the argument is FIXED BINARY, "flame" when FLOAT", etc. If the argument matches none of the choices "pathname" will be called. BAL 14, SUBRTN01 go to a subroutine, storing return address in R14 B TABLE(15) use returned value in reg 15 to index the branch table, branching to the appropriate branch instr. TABLE B OK return code =00 GOOD } B BAD return code =04 Invalid input } Branch table B ERROR return code =08 Unexpected condition } Improving readability of code by replacing a block of code with a function call where a descriptive function name serves to describe the block of code. This makes the calling code concise and readable even if the function is not meant to be reused. Improving traceability (i.e. most languages offer ways to obtain the call trace which includes the names of the involved functions and perhaps even more information such as file names and line numbers); by not decomposing the code into functions, debugging would be severely impaired 10 REM A BASIC PROGRAM 20 GOSUB 100 30 GOTO 20 100 INPUT "GIVE ME A NON-NEGATIVE NUMBER"; N 110 PRINT "THE SQUARE ROOT OF"; N; 120 PRINT "IS"; SQRT(N) 130 RETURN This code repeatedly asks the user to enter a number and reports the square root of the value. Lines 100-130 are the callable. Sub SayHello TextWindow.WriteLine("Hello!") EndSub This can be called as SayHello() . Sub DoSomething() ' Some Code Here End Sub The does not return a value and has to be called stand-alone, like DoSomething Function GiveMeFive() as Integer GiveMeFive= 5 End Function This returns the value 5, and a call can be part of an expression like y = x + GiveMeFive() Sub AddTwo(ByRef intValue as Integer) intValue = intValue + 2 End Sub This has a side-effect modifies the variable passed by reference and could be called for variable v like AddTwo(v) . Giving v is 5 before the call, it will be 7 after. void doSomething() { // some code } This function does not return a value and is always called stand-alone, like doSomething() int returnFive() { return 5; } This function returns the integer value 5. The call can be stand-alone or in an expression like y = x + returnFive() void addTwo(int* pi) { *pi += 2; } This function has a side-effect modifies the value passed by address to the input value plus 2. It could be called for variable v as addTwo(&v) where the ampersand (&) tells the compiler to pass the address of a variable. Giving v is 5 before the call, it will be 7 after. void addTwo(int& i) { i += 2; } This function requires C++ would not compile as C. It has the same behavior as the preceding example but passes the actual parameter by reference rather than passing its address. A call such as addTwo(v) does not include an ampersand since the compiler handles passing by reference without syntax in the call. change_sign: procedure(array); declare array(*,*) float; array = -array; end change_sign; This could be called with various arrays as follows: /* first array bounds from -5 to +10 and 3 to 9 */ declare array1 (-5:10, 3:9)float; /* second array bounds from 1 to 16 and 1 to 16 */ declare array2 (16,16) float; call change_sign(array1); call change_sign(array2); ===Python=== In Python, the keyword def denotes the start of a function definition. The statements of the function body follow as indented on subsequent lines and end at the line that is indented the same as the first line or end of file. def format_greeting(name: str) -> str: return f"Welcome, {name}!" def greet_martin() -> None: print(format_greeting("Martin")) The first function returns greeting text that includes the name passed by the caller. The second function calls the first and is called like greet_martin() to write "Welcome Martin" to the console. mother_child(elizabeth, charles). father_child(charles, william). father_child(charles, harry). parent_child(X, Y) :- mother_child(X, Y). parent_child(X, Y) :- father_child(X, Y). Notice that the motherhood function, X = mother(Y) is represented by a relation, as in a relational database. However, relations in Prolog function as callable units. For example, the procedure call ?- parent_child(X, charles) produces the output X = elizabeth . But the same procedure can be called with other input-output patterns. For example: ?- parent_child(elizabeth, Y). Y = charles. ?- parent_child(X, Y). X = elizabeth, Y = charles. X = charles, Y = harry. X = charles, Y = william. ?- parent_child(william, harry). no. ?- parent_child(elizabeth, charles). yes.
