Format
#include <assert.h> void assert(int expression);
Language Level: ANSI, POSIX, XPG4
assert prints a diagnostic message to stderr and aborts the
program if expression is false (zero). The diagnostic
message has the format:
Assertion failed: expression, file filename, line line-number.
assert takes no action if the expression is true (nonzero).
Use assert to identify program logic errors. Choose an expression that holds true only if the program is operating as you intend. After you have debugged the program, you can use the special no-debug identifier NDEBUG to remove the assert calls from the program. If you define NDEBUG to any value with a #define directive, the C preprocessor expands all assert invocations to void expressions. If you use NDEBUG, you must define it before you include <assert.h> in the program.
Return Value
There is no return value.
Note: assert is implemented as a macro. Do not use the #undef directive with assert.
Example
In this example, assert tests string for a
null string and an empty string, and verifies that length
is positive before processing these arguments.
#include <stdio.h> #include <assert.h>
void analyze (char *, int);
int main(void)
{
char *string = "ABC";
int length = 3;
analyze(string, length);
printf("The string %s is not null or empty, "
"and has length %d \n", string, length);
}
void analyze(char *string, int length)
{
assert(string != NULL); /* cannot be NULL */
assert(*string != '\0'); /* cannot be empty */
assert(length > 0); /* must be positive */
/*********************************************************
The output should be:
The string ABC is not null or empty, and has length 3 *********************************************************/ }
![]()
abort -- Stop a Program
<assert.h>