There are many ways to debug a program, perhaps the most elementary is using a printf() statement to show important pieces of information regarding the program execution point, variable value, and loop and branch operation.
The solution also answers the following questions.
How can you use the printf() statement?
Where will you place them?
How is it useful to use #define in aid of printf() debugging?
SOLUTION This solution is FREE courtesy of BrainMass!
A printf() statement can help you look deep into the action of a program. Although it is used to spot errors and faults but remember it is a non-interactive way of finding what is sometimes equivalent of a "needle in a haystack". I list some of the placec you can insert a printf() for possible error checking:
1) Immediately after a scanf() to confirm the data you are reading conforms to the type and variable you as expected.
printf("Please enter a value between 0 and 100");
/*inserting a printf() statement here should reveal your mistake, yes a missing &*/
2) Use printf() to check the content of variables at the beginning, midway and end of a calculation
You should realize that placing so many printf() statement soon becomes a mess, because many of the printf() is not really necessary for the program functioning and even sometimes are counter-productive. There is a way to switch between debug mode and normal mode by defining DEBUG as follows:
printf("The values of the variablesare : %d, %f, %sn", *p, *p, str);
You can specify a DEBUG define at compile time by issuing gcc with the -DDEBUG command option or you can simply insert at the beginning of your source code:
Ofcourse, in this case you will have to recompile with this line commented(or deleted) if you want to compile without DEBUG support.
So, the idea is to always surround your printf()s with DEBUG defines in order to ease in finding the special DEBUG printf()s which are disposable and also different from regular printf()s.
3) Another way to find problems in a big program is to scatter printf()s in your important functions, so that you knows when the program is exiting prematurely. For
example, you might do something like this in your source code:
myplot(int x, int y)
printf("Entering myplot()n"); fflush(stdout);
---- lots of code here ------
printf("Exiting myplot()n"); fflush(stdout);
The fflush() command ensures that the print statement is sent to your
screen immediately, and you should use it if you're using printf()'s for