< previous page page_371 next page >

Page 371
stars. When this happens, you might assume that PrintData has gone haywire, but it's the main function's fault for not checking the validity of the data. (The program should perform this test in function GetData). Thus, a side effect of one function can multiply and give the appearance of errors elsewhere in a program. We take a closer look at the concept of side effects in the next chapter.
The assert Library Function
We have discussed how function preconditions and postconditions are useful for debugging (by checking that the precondition of each function is true prior to a function call, and by verifying that each function correctly transforms the precondition into the postcondition) and for testing (by pushing the precondition to its limits and even violating it). To state the preconditions and postconditions for our functions, we've been writing the assertions as program comments:
// Precondition:
//     studentCount > 0
All comments, of course, are ignored by the compiler. They are not executable statements; they are for humans to examine.
On the other hand, the C++ standard library gives us a way in which to write executable assertions. Through the header file assert.h, the library provides a void function named assert. This function takes a logical (Boolean) expression as a parameter and halts the program if the expression is false. Here's an example:
#include <assert.h>
.
.
.
assert(studentCount > 0);
average = sumOfScores / studentCount;
The parameter to the assert function must be a valid C++ logical expression. If its value is nonzero (TRUE), nothing happens; execution continues on to the next statement. If its value is zero (FALSE), execution of the program terminates immediately with a message stating the assertion as it appears in the parameter list, the name of the file containing the program source code, and the line number in the program. In the example above, if the value of studentCount is less than or equal to zero, the program halts after printing a message like this:
Assertion failed: studentCount > 0, file myprog.cpp, line 48

 
< previous page page_371 next page >