cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : C Library : cassert (assert.h) : assert
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cassert (assert.h)
assert

-

assert macro
void assert (int expression);
<cassert>

Evaluate assertion

If the argument expression of this macro with functional form compares equal to zero (i.e., the expression is false), a message is written to the standard error device and abort is called, terminating the program execution.

The specifics of the message shown depend on the specific implementation in the compiler, but it shall include: the expression whose assertion failed, the name of the source file, and the line number where it happened. A usual expression format is:

Assertion failed: expression, file filename, line line number

This macro is disabled if at the moment of including assert.h a macro with the name NDEBUG has already been defined. This allows for a coder to include many assert calls in a source code while debugging the program and then disable all of them for the production version by simply including a line like:

#define NDEBUG
at the beginning of its code, before the inclusion of assert.h.

Parameters

expression
Expression to be evaluated. If this expression evaluates to 0, this causes an assertion failure that terminates the program.

Return Value

none

Example

/* assert example */
#include <stdio.h>
#include <assert.h>

int main ()
{
  FILE * datafile;
  datafile=fopen ("file.dat","r");
  assert (datafile);

  fclose (datafile);

  return 0;
}

In this example, assert is used to abort the program execution if datafile compares equal to 0, which happens when the previous call to fopen was not successful.

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us