6.1.2 assert Macro
If the argument is false, an assertion failure message is printed and the program is aborted.
Include
<assert.h>
Prototype
void assert(scalar
expression);
Argument
expression
- The expression to test.
Remarks
The expression evaluates to zero or non-zero. If zero, the assertion fails, a message is
printed and abort()
is called, terminating program execution. In the
case of MPLAB XC8, the message is printed to stdout
; for other
compilers, this is printed to stderr
.
The message includes the source file name (__FILE__
), the source line
number (__LINE__
), and the expression being evaluated.
If the macro NDEBUG
(see NDEBUG Macro) is defined at the
point where <assert.h>
is included, the assert()
macro will evaluate to a void expression, ((void)0)
, and not print any
assertion message, nor abort program execution. Inclusion of
<assert.h>
can occur multiple times, even in the same source
file, and the action of the assert()
macro for each inclusion will be
based on the state of NDEBUG
at the point at which that inclusion takes
place.
Example
See the notes at the beginning of this chapter or section for
information on using printf()
or scanf()
(and other functions reading and writing the stdin
or
stdout
streams) in the example code.
int main(void)
{
int a;
a = 4;
#define NDEBUG /* negate debugging - disable assert() functionality */
#include <assert.h>
assert(a == 6); /* no action performed, even though expression is false */
#undef NDEBUG /* ensure assert() is active */
#include <assert.h>
a = 7;
assert(a == 7); /* true - no action performed */
assert(a == 8); /* false - print message and abort */
}
Example Output
sampassert.c:14 a == 8 -- assertion failed
ABRT