Using the assert macro in C++

April 9th, 2009 by carlos


Writing good software is a difficult proposition. It is sometimes easy to write sub-par software, with a high number of defects and poor maintainability, but to make sure that software has good quality and is easy to modify one needs to take care of many issues.

One of the necessary factors in creating good software is guaranteeing that it satisfy its requirements. One of the simplest methods for doing this is using the assert facility provided by the standard C++ library.

Using Assert

Assert is a mechanism that allows a program to stop an error in its tracks whenever it is detected.  Assert is implemented in C++ as a macro, where the first argument is a boolean expression. This expression is evaluated, and its result is always expected to be true.

For example, the following is a typical use of assert:

void test(int value) {
  assert(value > 0);
  // normal processing

In the example above, the assert tests if the argument passed to function test is greater than zero. If this is true, processing continues as normal. However, in the case that value is negative or zero, the assertion fails and the program stops immediately.

The assert macro is defined in assert.h, a header file that is  also used by the C compiler — so you can use assert on C or C++.

Using assert in a testing environment is a first step towards guaranteeing that we have the correct values before our algorithm starts. It is an easy method and has been effectly used in this way by many experienced programmers. 

Disadvantages of Assert

Although there are many advantages on using assert, one also needs to be aware of the problems in its use. First, asserts are not a substitute to using exceptions. When there is a possibility of recovery from an error, then the exception mechanism should be used. This way, the programmer has control over how a failure in the code must be handled. With an assert, on the other hand, the whole program stops.

In general, asserts should not be used on production code. The reason is that asserts are not graceful, they just stablish that an error ocurred, and stop the program. This is certainly not the behavior required in production, where the appropriate steps need to be taken to guarantee that user data is preserved.

Conclusion

Asserts are a powerful mechanism provided by C++ to guarantee that certain conditions are present on a specific function. If the expression given as input is not true, then the assert will automatically call the attention of the developer.

Asserts should be used sparingly, however, and not at all in production. Thankfully, all implementations of assert have a mechanism to disable it in production code. Check the documentation of NDEBUG in your favorite compiler for the details.