< previous page page_416 next page >

Page 416
Background Information
Ignoring a Function Value
A peculiarity of the C++language is that it lets you ignore the value returned by a valuereturning function. For example, you could write the following statement in your program without any complaint from the compiler:
sqrt(x);
When this statement is executed, the value returned by sqrt is promptly discarded. This function call has absolutely no effect except to waste the computer's time by calculating a value that is never used.
Clearly, the above call to sqrt is a mistake. No programmer would write that statement intentionally. But C++ programmers occasionally write value-returning functions in a way that allows the caller to ignore the function value. Here is a specific example from the C++ standard library.
The library provides a function named remove, the purpose of which is to delete a disk file from the system. It takes a single parametera string specifying the name of the fileand it returns a function value. This function value is an integer notifying you of the status: zero if the operation succeeded, and nonzero if it failed. (Notice that this use of zero and nonzero is backwards from the result of testing the state of an I/O stream.) Here is how you might call the remove function:

(text box continued on next page)
If x is originally 2, what value is stored into y? The answer depends on the order in which your compiler evaluates the expression. If it first calls the function, then the answer is 7. If it accesses x first in preparation for adding it to the function result, the answer is 6. This is precisely why reference parameters shouldn't be used with value-returning functions. Obviously, a function that creates such an unpredictable situation has no place in a well-written program.
An exception is the case where an I/O stream variable is passed to a value-returning function; remember, C++ allows a stream variable to be passed only to a reference parameter. Within a value-returning function, the only operation that should be performed is testing the state of the stream (for EOF or I/O errors). A value-returning function should not perform input or output operations. Such operations are considered to be side effects of the

 
< previous page page_416 next page >