2.3 The abused cout debugging technique
The cout technique takes its names from the C++ statement for printing on the standard output stream (usually the terminal screen). It consists of adding print statements in the code to track the control flow and data values during code execution. Although it is the favourite technique of all the novices, it is unbelievable how many experienced programmers still refuse to evolve and abandon this absolutely time-wasting and very ad-hoc method.
Despite its popularity, this technique has strong disadvantages. First of all, it is very ad-hoc, because code insertion is temporary, to be removed as soon as the bug is fixed. A new bug means a new insertion, making it a waste of time. In debugging as well as in coding, the professional should aim to find reusable solutions whenever possible. Printing statements are not reusable, and so are deprecated. As we will see shortly, there are more effective ways to track the control flow through messages. In addition, printing statements clobber the normal output of the program, making it extremely confused. They also slow the program down considerably: accessing to the outputting peripherals becomes a bottleneck. Finally, often they do not help at all, because for performance reasons, output is usually buffered and, in case of crash, the buffer is destroyed and the important information is lost, possibly resulting in starting the debugging process in the wrong place.
In some (very few) circumstances cout debugging can be appropriate, although it can always be replaced by other techniques. For these cases, here are some tips. To begin with, output must be produced on the standard error, because this channel is unbuffered and it is less likely to miss the last information before a crash. Then, printing statements should not be used directly: a macro should be defined around them (as illustrated in listing 2) so to switch debugging code on and off easily. Finally, debugging levels should be used to manage the amount of debugging information.