Functions
Function Composition
Moreover, since a function call is an expression, we can use it as a part of an argument:
cout << Add( 4, Add(2,1) ) << endl;
The 'inner' Add
function gets evaluated to value 3, making this statement the same as (i.e.
equivalent to):
cout << Add( 4, 3 ) << endl;
It outputs the number 7.
To make it more fun, let us add a function for multiplication:
double Mul(double a, double b) { return a*b; }
This function has
two parameters, named a
and b
. We also say that this function
accepts
two arguments, or that it takes two arguments or
values as input. Also, the arguments get passed to
the function, or more precisely, the arguments get passed to their respective
parameters.
It might be confusing that the Add
and Mul
functions have parameters with the same names, but that is allowed because the
names of parameters are local to the function, that is, the names of parameters
are not visible outside the function definition.
To calculate 2 + 4*3
and
write out the result, we can write:
cout << Add(2, Mul(4,3)) << endl;
To calculate (8+2)*4
and
write out the result, we can write:
cout << Mul(Add(8,2), 4) << endl;
To calculate 8*3 + 4*2*3
and write out the result, we can write:
cout << Add( Mul(8,3), Mul(Mul(4,2),3) ) << endl;
The chaining of functions as demonstrated in the examples above is called function composition.
A few guidelines will be provided here in case you are unsure how to transform the common way of writing arithmetic expressions into functional form.
You should start from innermost expressions and proceed outwards. The innermost expressions are those that have to be calculated before others. For example:
8*3 Mul(8,3) 4*2 Mul(4,2) 4*2*3 Mul(Mul(4,2),3) 8*3 + 4*2*3 Add( Mul(8,3), Mul(Mul(4,2),3) )
Another way to make this task easier is to first add all the parentheses to the common arithmetic expression. One pair of parentheses has to be added for each operator while respecting the order of operations as dictated by the usual rules of priority. For example:
8*3 + 4*2*3 ((8*3) + ((4*2)*3))
Then you can replace the operators by function calls one by one. You can do it in any order. Let us try proceeding from left to right:
((8*3) + ((4*2)*3)) Add((8*3) , ((4*2)*3)) Add(Mul(8,3) , ((4*2)*3)) Add(Mul(8,3) , Mul((4*2),3)) Add(Mul(8,3) , Mul(Mul(4,2),3))
After you have completed reading this tutorial, you can choose to continue with Interactive Computer Graphics Tutorial or Beginner's Algorithms Tutorial. We recommend the Beginner's Algorithms tutorial, but everyone likes graphics more.