The C assert( ) macro
In the standard header file
<cassert>
you’ll find assert( ), which is a convenient debugging
macro. When you use assert( ), you give it an argument that is an
expression you are “asserting to be true.” The preprocessor
generates code that will test the assertion. If the assertion isn’t true,
the program will stop after issuing an error message telling you what the
assertion was and that it failed. Here’s a trivial
example:
//: C03:Assert.cpp
// Use of the assert() debugging macro
#include <cassert> // Contains the macro
using namespace std;
int main() {
int i = 100;
assert(i != 100); // Fails
} ///:~
The macro originated in Standard C, so
it’s also available in the header file assert.h.
When you are finished debugging, you can
remove the code generated by the macro by placing the line:
#define NDEBUG
in the program
before the inclusion of <cassert>, or by defining NDEBUG on the
compiler command line. NDEBUG is a flag used in <cassert> to change
the way code is generated by the macros.
Later in this book, you’ll see some
more sophisticated alternatives to assert( ).