assert
The assert macro is used to define an assertion in C/C++ code. An assertion is a logic statment that must be true every time it is executed. Assertions are important to determine the correctness of a piece of code that is being tested.
The assert macro has only one parameter, which must be an expression with logical interpretation of true or false (which in C is represented by 0 (false) or non-zero (true)). The assert macro has an important side effect when it is called: if the expression passed as a parameter evaluates to true, nothing happens. Otherwise, if the value is evaluated to zero (false) then the program is immediately stop and an error message is printed stating the expression that caused the failure.
The behavior of the assert macro is very abrupt, and in general should not be present in code that is shipped to users. Therefore, the assert macro can be completely disable when the macro name NDEBUG is defined. The most common scenario of use for the NDEBUG constant is passing it to the compiler as a preprocessor definition (with the GCC compiler this can be done with the parameter -DNDEBUG).
Example
The following example shows how to use the assert macro:
#include#include #include int main() { int a = 10; int b = 5; int c; c = a + b; assert(c == 15); return 0; }
The code above perform a sum operation and then calls the assert function to make sure that the result is correct. The assert macro can be disabled by defining the NDEBUG symbol, using for example the following line before including the header file \"assert.h\":
#define NDEBUG
Post a comment