Functions
Function Call and Function Arguments
Let us examine the concept of functions in programming by looking at an example of a very simple function that is familiar to us all. It is a function for adding up two numbers, defined as follows:
double Add(double a, double b) { return a+b; }
This function, named Add
, has
two parameters, named a
and b
. The result of this function is the sum of its parameters. Both
parameters are of the type double
so that we can use this function to add any two numbers together and the result is of the type double
again.
This function is not very useful, as a much
more compact operator '+
' can be used instead of it, but here we need this function for
demonstration purposes. The following piece of code demonstrates how this
function might be used:
int main() { double k = Add(4,3); cout << k << endl; cout << Add(11,6) << endl; cout << Add(5-3,4) << endl; }
It outputs:
7 17 6
The first statement demonstrates that a
function value can be assigned to a variable, as can the result of any
expression of the appropriate type. The function Add
returns
the value 7.0
, and this value gets assigned to the variable k
, which
gets printed out by the next statement.
The next cout
statement prints out the number
17. The expression Add(11,6)
is a function call expression and it triggers the execution of the
function. The numbers 11 and 6 are called the arguments of a function call, and
the number of arguments must match the number of the function's parameters. Upon
executing a function call, the values of the arguments get assigned to the
function's parameters and the execution of the function proceeds afterwards. We
also say the values of arguments in a function call get passed to the function's parameters.
The type of each argument has to match the
type of the corresponding parameter. Alternatively, the type of an argument
must be convertible to the type of the corresponding parameter, as in our
case where the arguments of type int
get converted to type double
.
The arguments of a function are expressions
like any other. The arguments get evaluated before the function is called, which
is a feature of C++ and many other languages called eager
evaluation. In the final cout
statement, the first argument is
the expression 5-3
and the second one is 4
. The first expression gets
evaluated to value 2, and the second one to value 4, and those two values are
then assigned to the parameters of a function which then gets executed.
We can use variables as parts of function argument expressions:
double j = 4; cout << Add(j-1, j*j) << endl;
Before the function call is made, the first argument gets evaluated to the value 3, and the second argument gets evaluated to the value 16. The output is 19.