Also, of course, one name for the fundamental unit of
modularity in a computer program,
also called
subroutine or
procedure.
Externally, a function is known by a name,
accepts zero or more
arguments or
parameters describing the data it is to do its work on,
and returns a
value reporting the result. (The analogy with mathematical functions is clear.)
Ideally, a function implements an
abstraction,
in a
black box way:
it performs some useful service,
but you don't know (and don't care) how it does it.
Theoretically, it should always be possible to rewrite the internal implementation of a function -- to fix a bug, or improve performance, or add a feature -- and, as long as the parameter list doesn't change, for the rewrite to be
transparent to the function's callers, such that none of them have to make any corresponding changes themselves.
Examples (suggested by wharfinger):
A C function to return the average of two numbers:
int average(int a, int b)
{
return (a + b) / 2;
}
A Pascal function for computing the greatest common divisor (from Jensen & Wirth, Pascal: User Manual and Report, 2/E, p. 82):
function gcd(m,n: integer):integer;
begin if n=0 then gcd := m
else gcd := gcd(n,m mod n)
end;