|
|
|
|
|
|
|
6. With a value-returning function, be sure the function heading and prototype begin with the correct data type for the function return value. |
|
|
|
|
|
|
|
|
7. With a value-returning function, don't forget to use a statement |
|
|
|
 |
|
|
|
|
return Expression; |
|
|
|
 |
|
|
|
|
to return the function value. Make sure the expression is of the correct type, or implicit type coercion will occur. |
|
|
|
|
|
|
|
|
8. Remember that a call to a value-returning function is part of an expression, whereas a call to a void function is a separate statement. (C++ softens this distinction, however, by letting you call a value-returning function as if it were a void function, ignoring the return value. Be careful here.) |
|
|
|
|
|
|
|
|
9. In general, don't use reference parameters in the formal parameter list of a value-returning function. A reference parameter must be used, however, when an I/O stream variable is passed as a parameter. |
|
|
|
|
|
|
|
|
10. If necessary, use debug output statements to indicate when a function is called and if it is executing correctly. The values in the actual parameters can be printed immediately before (to show the incoming values) and immediately after (to show the outgoing values) the call to the function. You may want to use debug output statements in the function itself to indicate what happens each time it is called. |
|
|
|
|
|
|
|
|
The scope of an identifier refers to the parts of the program in which it is visible. C++ functions have global scope, as do variables and constants that are declared outside all functions. Variables and constants declared within a block have local scope; they are not visible outside the block. The formal parameters of a function have the same scope as local variables declared in the outermost block of a function. |
|
|
|
|
|
|
|
|
With rare exceptions, it is not considered good practice to declare global variables and reference them directly from a function. All communication between the modules of a program should be through the formal and actual parameter lists (and via the function value sent back by a value-returning function). The use of global constants, on the other hand, is considered to be an acceptable programming practice because it adds consistency and makes a program easier to change while avoiding the pitfalls of side effects. Welldesigned and well-documented functions that are free of side effects can often be reused in other programs. Many programmers keep a library of functions that they use repeatedly. |
|
|
|
|
|
|
|
|
The lifetime of a variable is the period of time during program execution when memory is allocated to it. Global variables have static lifetime (memo- |
|
|
|
|
|