DekGenius.com
Team LiB   Previous Section   Next Section

13.3 <cassert>

The <cassert> header (from the C standard <assert.h> header) declares the assert macro. The <cassert> header is unique in that you can #include it multiple times to obtain different effects (depending on whether the NDEBUG macro is defined at the time of #include <cassert>).

Assertions are checked at runtime. You can use templates to craft compile-time assertions. See Appendix B for information about the Boost project, which supports compile-time assertions.

Instead of assertions, consider using exceptions, which offer more flexibility and control.

assert macro Checks an assertion at runtime

void assert(int expression)

figs/acorn.gif

If enabled, the assert macro ensures the expression is true (nonzero). If so, nothing happens, and execution continues normally. If the expression evaluates to 0, assert prints a message to the standard error file and calls abort. The format of the message is implementation-defined, but it includes a textual representation of expression and the filename and line number where the assert call appears (that is, the values of the _ _FILE_ _ and _ _LINE_ _ macros).

If disabled, the assert macro does not evaluate expression and has no effect.

See Also

abort function in <cstdlib>, throw keyword

NDEBUG macro Enables or disables compilation of assertions

#define NDEBUG
#include <cassert>

The NDEBUG macro is not defined by <cassert> or anywhere else in the standard C++ library. Instead, you can define the macro before including the <cassert> header to disable the assert macro.

In one source file, you can define and undefine NDEBUG multiple times, each time followed by #include <cassert>, to enable or disable the assert macro multiple times in the same source file.

See Also

assert macro

    Team LiB   Previous Section   Next Section