assert.h

assert.h is a header file in the standard library of the C programming language that defines the C preprocessor macro assert().[1] [2] The macro implements an assertion, which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false. In C++ it is also available through the cassert header file.

When executed, if the expression is false (that is, compares equal to 0), assert() writes information about the call that failed on stderr and then calls abort(). The information it writes to stderr includes:

Example output of a program compiled on Linux:

program: program.c:5: main: Assertion `a != 1' failed.
Abort (core dumped)

Programmers can eliminate the assertions just by recompiling the program, without changing the source code: if the macro NDEBUG is defined before the inclusion of <assert.h>, the assert() macro may be defined simply as:

#define assert(ignore)((void) 0)

and therefore has no effect on the compilation unit, not even evaluating its argument. Therefore expressions passed to assert() must not contain side-effects since they will not happen when debugging is disabled. For instance:

assert(x = gets());

will not read a line and not assign to x when debugging is disabled.

Example

#include <stdio.h>
#include <assert.h>

int test_assert ( int x )
{
   assert( x <= 4 );
   return x;
}

int main ( void ) 
{
  int i;

    for (i=0; i<=9; i++){
        test_assert( i );
        printf("i = %d\n", i);
    }

  return 0;
}
i = 0
i = 1
i = 2
i = 3
i = 4
assert: assert.c:6: test_assert: Assertion `x <= 4' failed.
Aborted

External links

References

  1. 1 2 International Standard for Programming Language C (C99), ISO/IEC 9899:1999, p. 169
  2. [Coding Programmer Page C / C++ Reference].
This article is issued from Wikipedia - version of the Saturday, October 17, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.