Number
int64
1
7.61k
Text
stringlengths
2
3.11k
2,301
In computer programming, a function, subprogram, procedure, method, routine or subroutine is a callable unit that has a well-defined behavior and can be invoked by other software units to exhibit that behavior.
2,302
Callable units provide a powerful programming tool. The primary purpose is to allow for the decomposition of a large and/or complicated problem into chunks that have relatively low cognitive load and to assign the chunks meaningful names . Judicious application can reduce the cost of developing and maintaining software...
2,303
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 a...
2,304
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...
2,305
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 comp...
2,306
Subroutines were implemented in Konrad Zuse's Z4 in 1945.
2,307
In 1945, Alan M. Turing used the terms "bury" and "unbury" as a means of calling and returning from subroutines.
2,308
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
2,309
In other words, one can designate subroutine A as division and subroutine B as complex multiplication and subroutine C as the evaluation of a standard error of a sequence of numbers, and so on through the list of subroutines needed for a particular problem. ... All these subroutines will then be stored in the machine, ...
2,310
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.
2,311
Goldstine and von Neumann wrote a paper dated 16 August 1948 discussing the use of subroutines.
2,312
Some very early computers and microprocessors, such as the IBM 1620, the Intel 4004 and Intel 8008, and the 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 recur...
2,313
The DEC PDP-6 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 , PDP-11 and VAX-11 lines followed suit; this feature also supports both arbitrarily deep subroutine nesting and ...
2,314
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...
2,315
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.
2,316
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.
2,317
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 ; and the same subroutine tape could then be used by many different programs. A similar approach was used in ...
2,318
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.
2,319
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.
2,320
Another advance was the jump to subroutine instruction, which combined the saving of the return address with the calling jump, thereby minimizing overhead significantly.
2,321
In the IBM System/360, for example, 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 through that register. If ...
2,322
In systems such as the HP 2100, the JSB instruction would perform a similar task, except that the return address was stored in the memory location that was the target of the branch. Execution of the procedure would actually begin at the next memory location. In the HP 2100 assembly language, one would write, for exampl...
2,323
to call a subroutine called MYSUB from the main program. The subroutine would be coded as
2,324
The JSB instruction placed the address of the NEXT instruction into the location specified as its operand , and then branched to the NEXT location after that . 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.
2,325
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.
2,326
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 re...
2,327
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 spa...
2,328
The call sequence can be implemented by a sequence of ordinary instructions and very long instruction word architectures), but many traditional machines designed since the late 1960s have included special instructions for that purpose.
2,329
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.
2,330
Some designs, notably some Forth implementations, used two separate stacks, one mainly for control information 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.
2,331
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 of each procedure. At any moment, the stack contains only the private data of the calls that are currently a...
2,332
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.
2,333
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.
2,334
One disadvantage of the call stack mechanism is the increased cost of a procedure call and its matching return. The extra cost includes incrementing and decrementing the stack pointer , and accessing the local variables and parameters by frame-relative addresses, instead of absolute addresses. The cost may be realized ...
2,335
This overhead is most obvious and objectionable in leaf procedures or leaf functions, which return without making any procedure calls themselves. To reduce that overhead, many modern compilers try to delay the use of a call stack until it is really needed. For example, the call of a procedure P may store the return add...
2,336
In general, a callable unit is a list of instructions that, starting at the first instruction, executes sequentially except as directed via its internal logic. It can be invoked many times during the execution of a program. Execution continues at the next instruction after the call instruction when it returns control.
2,337
The features of implementations of callable units evolved over time and varies by context. This section describes features of the various common implementations.
2,338
Most modern programming languages provide features to define and call functions, including syntax for accessing such features, including:
2,339
Some languages, such as Pascal, Fortran, Ada and many dialects of BASIC, use a different name for a callable unit that returns a value vs. one that does not . Other languages, such as C, C++, C# and Lisp, use only one name for a callable unit, function. The C-family languages use the keyword void to indicate no retur...
2,340
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.
2,341
A callable unit that does not return a value is called as a stand-alone statement like print. This syntax can also be used for a callable unit that returns a value, but the return value will be ignored.
2,342
Some older languages require a keyword for calls that do not consume a return value, like CALL print.
2,343
Most implementations, especially in modern languages, support parameters which the callable declares as formal parameters. A caller passes actual parameters, a.k.a. arguments, to match. Different programming languages provide different conventions for passing arguments.
2,344
In some languages, such as BASIC, a callable has different syntax for a callable that returns a value vs. one that does not. In other languages, the syntax is the same regardless. In some of these languages an extra keyword is used to declare no return value; for example void in C, C++ and C#. In some languages, such...
2,345
In many contexts, a callable may have side effect behavior such as modifying passed or global data, reading from or writing to a peripheral device, accessing a file, halting the program or the machine, or temporarily pausing program execution.
2,346
In strictly functional programming languages such as Haskell, a function can have no side effects, which means it cannot change the state of the program. Functions always return the same result for the same input. Such languages typically only support functions that return a value, since there is no value in a function...
2,347
Most contexts support local variables – memory owned by a callable to hold intermediate values. These variables are typically stored in the call's activation record on the call stack along with other information such as the return address.
2,348
If supported by the language, a callable may call itself, causing its execution to suspend while another nested execution of the same callable executes. Recursion is a useful means to simplify some complex algorithms and break down complex problems. Recursive languages provide a new copy of local variables on each call...
2,349
Languages going back to ALGOL, PL/I and C and modern languages, almost invariably use a call stack, usually supported by the instruction sets to provide an activation record for each call. That way, a nested call can modify its local variables without effecting any of the suspended calls variables.
2,350
Recursion allows direct implementation of functionality defined by mathematical induction and recursive divide and conquer algorithms. Here is an example of a recursive function in C/C++ to find Fibonacci numbers:
2,351
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...
2,352
Some languages, e.g., Ada, Pascal, PL/I, Python, support declaring and defining a function inside, e.g., a function body, such that the name of the inner is only visible within the body of the outer.
2,353
If a callable can be executed properly even when another execution of the same callable is already in progress, that callable is said to be reentrant. A reentrant callable is also useful in multi-threaded situations since multiple threads can call the same callable without fear of interfering with each other. In the IB...
2,354
Some languages support overloading – allow multiple callables with the same name in the same scope, but operating on different types of input. Consider the square root function applied to real number, complex number and matrix input. The algorithm for each type of input is different, and the return value may have a dif...
2,355
Overloading is supported in many languages that support strong typing. Often the compiler selects the overload to call based on the type of the input arguments or it fails if the input arguments do not select an overload. Older and weakly-typed languages generally do not support overloading.
2,356
Here is an example of overloading in C++, two functions Area that accept different types:
2,357
PL/I has the GENERIC attribute to define a generic name for a set of entry references called with different types of arguments. Example:
2,358
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.
2,359
A closure is a callable plus values of some of its variables captured from the environment in which it was created. Closures were a notable feature of the Lisp programming language, introduced by John McCarthy. Depending on the implementation, closures can serve as a mechanism for side-effects.
2,360
Besides its happy path behavior, a callable may need to inform the caller about an exceptional condition that occurred during its execution.
2,361
Most modern languages support exceptions which allows for exceptional control flow that pops the call stack until an exception handler is found to handle the condition.
2,362
Languages that do not support exceptions can use the return value to indicate success or failure of a call. Another approach is to use a well-known location like a global variable for success indication. A callable writes the value and the caller reads it after a call.
2,363
In the IBM System/360, where return code was expected from a subroutine, the return value was often designed to be a multiple of 4—so that it could be used as a direct branch table index into a branch table often located immediately after the call instruction to avoid extra conditional tests, further improving efficien...
2,364
A call has runtime overhead, which may include but is not limited to:
2,365
Various techniques are employed to minimize the runtime cost of calls.
2,366
Some optimizations for minimizing call overhead may seem straight forward, but cannot be used if the callable has side effects. For example, in the expression -1)/+1), the function f cannot be called only once with its value used two times since the two calls may return different results. Moreover, in the few languages...
2,367
Inlining eliminates calls for particular callables. The compiler replaces each call with the compiled code of the callable. Not only does this avoid the call overhead, but it also allows the compiler to optimize code of the caller more effectively by taking into account the context and arguments at that call. Inlining,...
2,368
Callables can be defined within a program, or separately in a library that can be used by multiple programs.
2,369
A compiler translates call and return statements into machine instructions according to a well-defined calling convention. For code compiled by the same or a compatible compiler, functions can be compiled separately from the programs that call them. The instruction sequences corresponding to call and return statements ...
2,370
A built-in function, or builtin function, or intrinsic function, is a function for which the compiler generates code at compile time or provides in a way other than for other functions. A built-in function does not need to be defined like other functions since it is built in to the programming language.
2,371
Advantages of breaking a program into functions include:
2,372
Compared to using in-line code, invoking a function imposes some computational overhead in the call mechanism.
2,373
A function typically requires standard housekeeping code – both at the entry to, and exit from, the function .
2,374
Many programming conventions have been developed regarding callables.
2,375
With respect to naming, many developers name a callable with a phrase starting with a verb when it does a certain task, with an adjective when it makes an inquiry, and with a noun when it is used to substitute variables.
2,376
Some programmers suggest that a callable should perform exactly one task, and if it performs more than one task, it should be split up into multiple callables. They argue that callables are key components in software maintenance, and their roles in the program must remain distinct.
2,377
Proponents of modular programming advocate that each callable should have minimal dependency on the rest of the codebase. For example, the use of global variables is generally deemed unwise, because it adds coupling between all callables that use the global variables. If such coupling is not necessary, they advise to r...
2,378
Early BASIC variants require each line to have a unique number that orders the lines for execution, provides no separation of the code that is callable, no mechanism for passing arguments or to return a value and all variables are global. It provides the command GOSUB where sub is short for sub procedure, subprocedure...
2,379
This code repeatedly asks the user to enter a number and reports the square root of the value. Lines 100-130 are the callable.
2,380
In Microsoft Small Basic, targeted to the student first leaning how to program in a text-based language, a callable unit is called a subroutine. The Sub keyword denotes the start of a subroutine and is followed by a name identifier. Subsequent lines are the body which ends with the EndSub keyword.
2,381
This can be called as SayHello.
2,382
In later versions of Visual Basic , including the latest product line and VB6, the term procedure is used for the callable unit concept. The keyword Sub is used to return no value and Function to return a value. When used in the context of a class, a procedure is a method.
2,383
Each parameter has a data type that can be specified, but if not, defaults to Object for later versions based on .NET and variant for VB6.
2,384
VB supports parameter passing conventions by value and by reference via the keywords ByVal and ByRef, respectively. Unless ByRef is specified, an argument is passed ByVal. Therefore, ByVal is rarely explicitly specified.
2,385
For a simple type like a number these conventions are relatively clear. Passing ByRef allows the procedure to modify the passed variable whereas passing ByVal does not. For an object, semantics can confuse programmers since an object is always treated as a reference. Passing an object ByVal copies the reference; not th...
2,386
The does not return a value and has to be called stand-alone, like DoSomething
2,387
This returns the value 5, and a call can be part of an expression like y = x + GiveMeFive
2,388
This has a side-effect – modifies the variable passed by reference and could be called for variable v like AddTwo. Giving v is 5 before the call, it will be 7 after.
2,389
In C and C++, a callable unit is called a function. A function definition starts with the name of the type of value that it returns or void to indicate that it does not return a value. This is followed by the function name, formal arguments in parentheses, and body lines in braces.
2,390
In C++, a function declared in a class is called a member function or method. A function outside of a class can be called a free function to distinguish it from a member function.
2,391
This function does not return a value and is always called stand-alone, like doSomething
2,392
This function returns the integer value 5. The call can be stand-alone or in an expression like y = x + giveMeFive
2,393
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 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.
2,394
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 does not include an ampersand since the compiler handles passing by reference without syntax in the call.
2,395
In PL/I a called procedure may be passed a descriptor providing information about the argument, such as string lengths and array bounds. This allows the procedure to be more general and eliminates the need for the programmer to pass such information. By default PL/I passes arguments by reference. A function to chan...
2,396
This could be called with various arrays as follows:
2,397
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.
2,398
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.
2,399
In the procedural interpretation of logic programs, logical implications behave as goal-reduction procedures. A rule of the form:
2,400
which has the logical reading: