Insert
Diagnostic
Information
Macro
assert
Syntax
#include
<assert.h>
void
assert(expression)
int
expression;
Defined
in
assert.
h
as
macros
Description
The assert macro tests
an
expression; depending
on
the value
of
the ex-
pression, assert either aborts execution and issues a message or continues
execution. This macro
is
useful for debugging.
Example
• If
expression
is
false, the assert macro writes information about the
particular call that failed
to
the standard output, and then aborts exe-
cution.
•
If
expression
is true, the assert macro does nothing.
The header
file that declares the assert macro refers
to
another macro,
NDEBUG.
If you have defined NDEBUG
as
a macro name when the
as-
sert
. h header
is
included in the source file, then the assert macro is de-
fined
as:
#define
assert(ignore)
If
NDEBUG
is
not
defined when
assert.
h is included, then the assert
macro
is
defined
as:
#define
assert(expr)
\
if
(!
(expr»
{
printf("Assertion
failed,
(expr),
file
%s,
line
%d\n",
__
FILE
____
LINE
__
)
abort
();
}
In this example,
an
integer i
is
divided by another integer
j.
Since
divid-
ing
by
0 is
an
illegal operation, the example
uses
the assert macro to test j
before the division.
If
j =0, assert issues a message and aborts the program.
int
i,
j;
assert(j);
q =
i/j;
6-21