< previous page page_241 next page >

Page 241
Testing and Debugging Hints
1. C++ has three pairs of operators that are similar in appearance but very different in effect: == and =, && and &, and | | and |. Double-check all of your logical expressions to be sure you're using the equals-equals, and-and, and or-or operators.
2. If you use extra parentheses for clarity, be sure that the opening and closing parentheses match up. To verify that parentheses are properly paired, start with the innermost pair and draw a line connecting them. Do the same for the others, working your way out to the outermost pair. For example,
0241-01.gif
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
And here is a quick way to tell whether you have an equal number of opening and closing parentheses. The scheme uses a single number (the magic number), whose value initially is 0. Scan the expression from left to right. At each opening parenthesis, add 1 to the magic number; at each closing parenthesis, subtract 1. At the final closing parenthesis, the magic number should be 0. For example,
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
if (((totaL/scores) > 50) && ((total/(scores - 1)) < 100))
0  123            2     1    23       4           32       10
3. Don't use =< to mean less than or equal to; only the symbol <= works. Likewise, => is invalid for greater than or equal to; you must use >= for this operation.
4. In an If statement, remember to use a { } pair if the then-clause or else-clause is a sequence of statements. And be sure not to put a semicolon after the right brace.
5. Echo-print all input data. This way you know that your input data are what they are supposed to be.
6. Test for bad data. If a data value must be positive, use an If statement to test the value. If the value is negative or 0, an error message should be printed; otherwise processing should continue. For example, the Activity program could have the following statement inserted after the second output statement (the echo print):
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
if (temperature > 120 || temperature < -35)
    cout << Temperature data is in error. << endl;
else
{
    .
    .
    .
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
This If statement tests the limits of reasonable temperatures and executes the rest of the program only if the data value is reasonable.
7. Take some sample values and try them by hand as we did for the Notices program. (There's more on this in Chapter 6.)
8. If your program reads data from an input file, it should verify that the file was opened successfully. Immediately after the call to the open function, an If statement should test the state of the file stream.

 
< previous page page_241 next page >