|
|
|
|
|
|
|
When to Use Value-Returning Functions |
|
|
|
|
|
|
|
|
There aren't any formal rules for determining when to use a void function and when to use a value-returning function, but here are some guidelines: |
|
|
|
|
|
|
|
|
1. If the module must return more than one value or modify any actual parameters, do not use a value-returning function. |
|
|
|
|
|
|
|
|
2. If the module must perform I/O, do not use a value-returning function. (This guideline is not universally agreed upon.) |
|
|
|
|
|
|
|
|
3. If there is only one value returned from the module and it is a Boolean value, a value-returning function is appropriate. |
|
|
|
|
|
|
|
|
4. If there is only one value returned and that value is to be used immediately in an expression, a value-returning function is appropriate. |
|
|
|
|
|
|
|
|
5. When in doubt, use a void function. You can recode any value-returning function as a void function by adding an extra outgoing parameter to carry back the computed result. |
|
|
|
|
|
|
|
|
6. If both a void function and a value-returning function are acceptable, use the one you feel more comfortable implementing. |
|
|
|
|
|
|
|
|
Value-returning functions were included in C++ to provide a way of simulating the mathematical concept of a function. The C++ standard library supplies a set of commonly used mathematical functions through the header file math.h. A list of these appears in Appendix C. |
|
|
|
|
|
|
|
|
Problem-Solving Case Study Reformat Names |
|
|
|
|
|
|
|
|
Problem: Write a program that reads names in the form |
|
|
|
|
|
|
|
|
and prints them out in the form |
|
|
|
|
|
|
|
|
The input may contain any number of blanks preceding the first name and between the first and last names. Each person's name is on a separate line of input. |
|
|
|
|
|