|
|
|
|
|
|
|
able is incremented within the loop. In a flag-controlled loop, make sure the flag eventually changes. |
|
|
|
|
|
|
|
|
And, as always, watch for the = versus == problem in While conditions as well as in If conditions. The statement |
|
|
|
 |
|
|
|
|
while (someVar = 5) // Wrong
{
.
.
.
} |
|
|
|
|
|
|
|
|
produces an infinite loop. The value of the assignment (not relational) expression is always 5, which is interpreted by the machine as TRUE. |
|
|
|
|
|
|
|
|
3. Check the loop termination condition carefully, and be sure that something in the loop causes it to be met. Watch closely for values that cause one iteration too many or too few (the off-by-1 syndrome). |
|
|
|
|
|
|
|
|
4. Write out the loop invariantthe consistent, predictable part of its behavior in each iteration. Look for patterns that the invariant establishes. Are they just what you want? Perform an algorithm walk-through to verify that all of the appropriate preconditions and postconditions occur in the right places. |
|
|
|
|
|
|
|
|
5. Trace the execution of the loop by hand with a code walk-through. Simulate the first few passes and the last few passes very carefully to see how the loop really behaves. |
|
|
|
|
|
|
|
|
6. Use a debugger if your system provides one. A debugger is a program that runs your program in slow motion, allowing you to execute one instruction at a time and to examine the contents of variables as they change. If you haven't already, check to see if a debugger is available on your system. |
|
|
|
|
|
|
|
|
7. If all else fails, use debug output statementsoutput statements inserted into a program to help debug it. They output a message that indicates the flow of execution in the program or reports the values of variables at certain points in the program. |
|
|
|
|
|
|
|
|
For example, if you want to know the value of variable beta at a certain point in a program, you could insert this statement: |
|
|
|
 |
|
|
|
|
cout << beta = << beta << endl; |
|
|
|
|
|
|
|
|
If this output statement is in a loop, you will get as many values of beta as there are iterations of the body of the loop. |
|
|
|
|
|
|
|
|
After you have debugged your program, you can remove the debug output statements or just precede them with // so that they'll be treated as comments. (This practice is referred to as commenting out a piece of |
|
|
|
|
|