< previous page page_69 next page >

Page 69
On the other hand, well-designed functions tend to be small. The vast majority of functions will be just a handful of lines of code.
Function Arguments
Function arguments do not have to all be of the same type. It is perfectly reasonable to write a function that takes an integer, two longs, and a character as its arguments.
Any valid C++ expression can be a function argument, including constants, mathematical and logical expressions, and other functions that return a value.
Using Functions as Parameters to Functions
Although it is legal to use a function that returns a value as a parameter to another function, it can create code that is hard to read and hard to debug.
As an example, each of the functions double(), triple(), square(), and cube() returns a value. You could write
Answer = (double(triple(square(cube(myValue)))));
This statement takes a variable, myValue, and passes it as an argument to the function cube(), whose return value is passed as an argument to the function square(), whose return value is in turn passed to triple(), and that return value is passed to double(). The return value of this doubled, tripled, squared, and cubed number is now passed to Answer.
It is difficult to be certain what this code does (was the value tripled before or after it was squared?), and if the answer is wrong it will be hard to figure out which function failed.
An alternative is to assign each step to its own intermediate variable:
unsigned long myValue = 2;
unsigned long cubed = cube(myValue);          // cubed = 8
unsigned long squared = square(cubed);           // squared = 64
unsigned long tripled = triple(squared);         // tripled = 192
unsigned long Answer = double(tripled);         // Answer = 384
Now each intermediate result can be examined, and the order of execution is explicit.
Parameters Are Local Variables
The arguments passed in to the function are local to the function. Changes made to the arguments do not affect the values in the calling function. This is known as passing by

 
< previous page page_69 next page >

If you like this book, buy it!