C++ Preprocessor: Always Assert Your Code Is Right - Implementing Assert
(Page 2 of 4 )
Though we will be implementing our customized version of assert here, all you need to do is include assert.h and you are ready to use the assert macro that comes with it:
// assert.h
#ifndef NDEBUG
void __assert(const char *, const char *, int);
#define assert(e) \
((e) ? (void)0 : __assert(#e,__FILE__,__LINE__))
#else
#define assert(unused) ((void)0)
#endif
The __assert helper function prints an error message to stderr and the program is halted by calling abort(). It is possible that the implementation that comes with your compiler varies slightly, but you get the idea.
Lets use a simple example function:
void writeString(char const *string) {
assert( 0 != string );
...
}
In the unfortunate situation that the pointer to string is NULL, execution will halt and you will be offered the possibility of opening the debugger and jumping to the location in the source where the assertion failed. This can be very handy as you can examine the call stack, memory, registers, and so forth, and are likely to catch the perpetrator red handed!
Next: Implementing a Simplified Assert >>
More C++ Articles
More By J. Nakamura