for beginning programmers.
-
Don't try to fix a bug before you've found the bug.
-
I know it's tempting. You know that there is a programming errorsomewhere around these lines of code. Hmmm..., there's an i*j. Perhapsit was meant to be i/j. Let's change it and maybe that'll help. Ibelieve that this kind of thought process is nearly alwayscounterproductive. Instead you should be examing the code. Is i*j whatyou intended to write? If so, then leave it alone and search elsewherefor the error.
The counterproductivity comes from the fact that making a randomchange can sometimes hide the real error. The program is crashing withi+1, so you change it to i--and the crash stops! Is this a good thing?Not if the correct value for the code was i+1. In that case, you arejust hiding the real source of the error.
Debugging is all about gathering more information.
-
When a program is not working, you must use a debugger (or othermeans) to find
the earliest point in the program where the state ofthe program differs from what you expect. As you step through aprogram, all the values are right and you expect that the else-branchof an if-else statement will be taken...but the program steps into theif-branch instead. Or everything is right and you expect that thevalue of i will be changed to 42, but it is changed to 24 instead.
Always concentrate on finding the earliest point in the execution ofthe program where the program's state differs from what you expected.
Another information-gathering technique is to start throwing thingsout of the program. Not permanently! (This technique should be done ona copy of your program, not on the original.) The goal in this case isto make a tiny program that still gives unexpected results. If youbring me a six-line program that is misbehaving, it will be easier forme to find the error than with a 600-line program.
Keep a running series of your code.
- As you modify your code, save a copy periodically. There are somesystems that will do this for you automatically, so that you canrecover any earlier stage. But if you don't have such a system, thenmake your own series of program000.cxx, program001.cxx, program002.cxx... Remove wrong code completely.
- Once you know that a piece of code is wrong, remove it from yourworking copy completely. Do not take it out with a comment (take itout completely).