In computer science, parameters are a way of allowing the same sequence of commands to operate on different data without re-specifying the instructions.
For example, take the following list of instructions:
- Take an object.
- Break it into little pieces.
- Throw it away.
For instance:
- Destroy rock.
- Destroy cake.
- Destroy car.
The sequence of instructions is usually made into a subprogram and the object to operate on is specified while invoking the subprogram. The actual value given to a subprogram while invoking it, viz. rock, cake or car is called an actual parameter or an argument and the placeholder within the subprogram used to describe the operations on the argument is called a formal parameter or simply a parameter.
On the technical level, input parameters are implemented as by value, while the other two types are implemented as by reference.Calling conventions
Parameters can be passed to subprograms in several ways:
swap (a, b)
{
tmp = a;
a = b;
b = tmp;
}
swap (x, tmp)
is called by macro-expansion (where x
has the value 42
and tmp
has the value 64
), the effect is for the caller to execute the following:
tmp = x;
x = tmp;
tmp = tmp;
42
in both x
and temp
.
Call by name may also not have the same effect as call by reference or copy-restore, as can be seen by the following example:
swap (a, b)
{
tmp = a;
a = b;
b = tmp;
}
swap (i, a[i])
is called by name (where a[i]
represents the ith element of an array a
, if i
happens to have the value 9
, what happens is the following:
tmp = a
, tmp
becomes 9
.
a = b
, a
(which evaluates to i
) gets the value stored in a[9]
and hence i
also gets that value.
b = tmp
, b
evaluates to a[i]
but by now i
has the value stored in a[9]
. Hence a[a[9]]
is modified and not a[9]
as intended. On the other hand call by reference and by copy-restore would both correctly swap the values stored in i
and a[i]
.
On a more conceptual level, one may distinguish between parameters for input, for output or both. Virtually all older programming languages regard output and both as identical, but more modern languages as C# make a distinction.