Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 113

5


More About Function Arguments ........................................................................


Any valid C++ expression can be a function argument, including constants, mathematical
and logical expressions, and other functions that return a value. The important thing is
that the result of the expression match the argument type that is expected by the function.
It is even valid for a function to be passed as an argument. After all, the function will
evaluate to its return type. Using a function as an argument, however, can make for code
that is hard to read and hard to debug.
As an example, suppose you have the functions myDouble(),triple(),square(), and
cube(), each of which returns a value. You could write
Answer = (myDouble(triple(square(cube(myValue)))));
You can look at this statement in two ways. First, you can see that the function
myDouble()takes the function triple()as an argument. In turn,triple()takes the
function square(), which takes the function cube()as its argument. The cube()func-
tion takes the variable,myValue, as its argument.
Looking at this from the other direction, you can see that 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 myDouble(). The return value of this dou-
bled, tripled, squared, and cubed number is now assigned 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 = myDouble(tripled); // Answer = 384
Now, each intermediate result can be examined, and the order of execution is explicit.

C++ makes it really easy to write compact code like the preceding example
used to combine the cube(), square(), triple(), and myDouble()functions.
Just because you can make compact code does not mean you should. It is
better to make your code easier to read, and thus more maintainable, than
to make it as compact as you can.

CAUTION

Free download pdf