Sams Teach Yourself C++ in 21 Days

(singke) #1
22: cout << “\nSecond assert: “ << endl;
23: ASSERT(x != 5);
24: cout << “\nDone. << endl”;
25: return 0;
26: }

First assert:

Second assert:
ERROR!! Assert x !=5 failed
on line 24
in file List2104.cpp

Done.
On line 1, the term DEBUGis defined. Typically, this is done from the command
line (or the IDE) at compile time, so you can turn this on and off at will. On lines
8–14, the ASSERT()macro is defined. Typically, this is done in a header file, and that
header (assert.hpp) is included in all your implementation files.
On line 5, the term DEBUGis tested. If it is not defined,ASSERT()is defined to create no
code at all. If DEBUGis defined, the functionality defined on lines 8–14 is applied.
The ASSERT()itself is one long statement split across seven source code lines as far as
the precompiler is concerned. On line 9, the value passed in as a parameter is tested; if it
evaluates false, the statements on lines 11–13 are invoked, printing an error message. If
the value passed in evaluates true, no action is taken.

Debugging with assert()..............................................................................


When writing your program, you will often know deep down in your soul that something
is true: A function has a certain value, a pointer is valid, and so forth. It is the nature of
bugs that what you know to be true might not be so under some conditions. For example,
you know that a pointer is valid, yet the program crashes. assert()can help you find
this type of bug, but only if you make it a regular practice to use assert()liberally in
your code. Every time you assign or are passed a pointer as a parameter or function
return value, be certain to assert that the pointer is valid. Any time your code depends on
a particular value being in a variable,assert()that that is true.
No penalty is assessed for frequent use of assert(); it is removed from the code when
you undefine debugging. It also provides good internal documentation, reminding the
reader of what you believe is true at any given moment in the flow of the code.

OUTPUT


762 Day 21


LISTING21.3 continued

ANALYSIS
Free download pdf