assert() — Verify Condition
| Standards/Extensions | C or C++ | Dependencies |
|---|---|---|
ISO C
POSIX.1 XPG4 XPG4.2 |
both |
Format
#include <assert.h>
void assert(int expression);
General Description
A macro that inserts diagnostics into a program. If the expression
is false (zero), a diagnostic message of the form shown below is printed
to stderr, and abort() is called to abnormally end the
program. The assert() macro takes no action if the expression is true
(nonzero).
The diagnostic message has the format:
Assertion failed: expression, file filename, line line-number.If you define NDEBUG to any value with a #define directive
or with the DEFINE compiler option, the preprocessor expands all assert()
invocations to void expressions.
Note: Using the
#undef directive with
the assert() macro results in undefined behavior. The assert() macro
uses _FILE_ and _LINE_.Returned Value
The assert() function has no returned value.
Example
CBC3BA08
/* CBC3BA08
In this example, the assert() macro tests the string argument for a
null string and an empty string, and verifies that the length argument
is positive before proceeding.
*/
#include <stdio.h>
#include <assert.h>
void analyze(char *, int);
int main(void)
{
char *string1 = "ABC";
char *string2 = "";
int length = 3;
analyze(string1, length);
printf("string1 %s is not null or empty, "
"and has length %d \n", string1, length);
analyze(string2, length);
printf("string2 %s is not null or empty,"
"and has length %d\n", string2, 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 */
}
Output
String1 ABC is not null or empty, and has length 3
Assertion failed: *string != '\0', file: CBC3BA08 C A1, line: 26