In mathematics, a function is defined as a relationship between defined values and one or more variables. For example, a simple math function may be:
y = 2x
In this example, the relationship of y to x is that y is twice as much as the value assigned to x. While math functions can be far more complex than this, most are simple relative to functions used in computer programming. This may be why math functions are often referred to as "expressions," while computer functions are often called "procedures" or "subroutines."
Computer functions are similar to math functions in that they may reference parameters, which are passed, or input into the function. If the example above were written as a computer function, "x" would be the input parameter and "y" would be the resulting output value. It might look something like this:
$y = 2 * x;
The above example is a very basic function. Most functions used in computer programs include several lines of instructions and may even reference other functions. A function may also reference itself, in which case it is called a recursive function. Some functions may require no parameters, while others may require several. While it is common for functions to return variables, many functions do not return any values, but instead output data as they run.
Functions are sometimes considered the building blocks of computer programs, since they can control both small and large amounts of data. While functions can be called multiple times within a program, they only need to be declared once. Therefore, programmers often create "libraries" of functions that can referenced by one or more programs. Still, the source code of large computer programs may contain hundreds or even thousands of functions.
Updated: December 28, 2010