
 |
![]() |
|
|
|
|
 |
Functions as Parameters to Functions
Even though it is legal, within C++, for one function to take as a parameter a second function that returns a value, it can cause code that is hard to read and difficult to debug.
Here is an example, let us say you have the functions add(), subtract(), square(), and cube(), each of which returns a value. You could write
 | |  | | |
Output = (add(subtract(square(cube(Value))))); |
|  |
|
This statement takes a variable, Value, and passes it as an argument to the function cube(), then the return value is passed as an argument to the function square(), whose return value is in turn passed to subtract(), and that return value is passed to add(). The return value of this add, subtract, squared, and cubed number is now passed to Output.
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 difficult to determine which function failed.
A better way, which we highly recommend, is to assign each step to its own intermediate variable:
 | |  | | |
long Value = 2;
long cubed = cube(Value);
long squared = square(cubed);
long tripled = subtract(squared);
long Answer = add(subtract); |
|  |
|
Now each result can be examined, and the order of execution is shown. We think you will agree that this is much simpler to both read and understand.
Please Rate this Code:
Comments for: Functions as Parameters to Functions
There are NO user contributed comments for Functions as Parameters to Functions.
|
 |
|
 |
|
|
|
|
|
|
|