Inheritance/Polymorphism  «Prev 

Standard File cerr Exceptions

The standard file cerr

C systems have stdin, stout, and stderr as standard files. The C++ stream input/output ties these standard files to cin, cout, and cerr respectively.
The standard file cerr is the output stream ostream corresponding to stderr. It is the standard stream for error output.
cerr is an object of class ostream that represents the standard error stream. It is associated with the cstdio stream stderr.
By default, most systems have their standard error output set to the console, where text messages are shown, although this can generally be redirected.
Because cerr is an object of class ostream, we can write characters to it either as formatted data using for example the insertion operator (ostream::operator<<) or as unformatted data using the write member function, among others (see ostream).

More preprocessor features

You almost always want to use inline functions instead of preprocessor macros.
The exceptions are when you need to use three special features in the C preprocessor (which is also the C++ preprocessor):
  1. stringizing,
  2. string concatenation, and
  3. token pasting.

Stringizing, introduced earlier in the book, is performed with the # directive and allows you to take an identifier and turn it into a character array. String concatenation takes place when two adjacent character arrays have no intervening punctuation, in which case they are combined. These two features are especially useful when writing debug code.
Thus,
#define DEBUG(x) cout << #x " = " << x << endl
This prints the value of any variable. You can also get a trace that prints out the statements as they execute:
#define TRACE(s) cerr << #s << endl; s
The #s stringizes the statement for output, and the second s reiterates the statement so it is executed. Of course, this kind of thing can cause problems, especially in one-line for loops:
for(int i = 0; i < 100; i++)
TRACE(f(i));
Because there are actually two statements in the TRACE( ) macro, the one-line for loop executes only the first one. The solution is to replace the semicolon with a comma in the macro.