Debugging via Standard Output

◀ Syntax Error Versus Logic Error▶ Debugging Using Debugging Tools
Amazon In C++ you use cout or printf() to print statements to standard output (stdout) channel. Using the output ability of a program is generally useful for debugging. It is very useful in the following three situations while a program is running:

In the first situation, the program hangs and must be terminated forcibly. To find out the cause we can insert print statements in different places and run the program again. Doing so generally enables us to locate where the hanging occurs.

In the second situation, the program exits after generating a segmentation fault. Most programmers would probably agree that a segmentation fault is the most annoying and elusive bug. Again, inserting print statements in several places generally helps you see where this fault is generated.

A detailed discussion about segmentation fault will be given in Chapter 9.
In the third situation, the program runs infinitely and does not exit until the operating system runs out of memory. Two of the most common sources of this problem are an infinite loop and infinite recursion.

In any case you need to make sure you “flush” the outputs in your print statements to make them printed on the screen immediately. See Chapter 16.2 for more details.

A common practice is to use #define DEBUG where you would like to print a debugging message. You wrap debugging statements in the #define block and you will only see those statements when you #define DEBUG. This way you can easily turn on and off debugging.

An alternative is to log the results instead of printing them on the screen. Once you run the program you can check the log.

Next let’s check out how we can debug using debugging tools!
◀ Syntax Error Versus Logic Error▶ Debugging Using Debugging Tools

Questions? Let me know!