Debugging With Assertions

19 Nov 2012

Assertion is a powerful tool that can be used for software debugging or automating tests (such as in Unit Testing).

In C/C++, assertions are optional, meaning that you can turn it on and off by supplying a single argument to the compiler. To elaborate, in C++, compile your code with g++ -DNDEBUG flag, then assertion is disabled; in C, make sure NDEBUG macro is defined before including <assert.h>, that is:

#define NDEBUG
#include <assert.h>

Of course, the trick that applies to C also applies to C++. Choose for yourself. In Python, compile your program with -O flag then assertion is disabled.

While assertions are quite convenient for testing the pre- and post-conditions of program routines or program invariants, there is one downside of putting them into your software: performance drag. Especially when the software is big and lots of assertions are embedded (and possibly within some complex data structures).

Therefore, try to use assertions wisely, especially in places that do not hit program performance too much and conditions are easily checked.