Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <assert.h>
void assert(int expression);
The assert() macro inserts diagnostics into a program. If the expression (which will have a scalar type) is false (that is, compares equal to 0), 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).
Assertion failed: expression, file filename, line line-number.
Assertion failed: expression, file filename, line line-number, function function-name.
If you define NDEBUG to any value with a #define directive or with the DEFINE compiler option, the C/C++ preprocessor expands all assert() invocations to void expressions.
assert() returns no values.
⁄* CELEBA08
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 *⁄
}
String1 ABC is not NULL or empty, and has length 3
Assertion failed: *string != '\0', file: CELEBA08 C A1, line: 26
String1 ABC is not NULL or empty, and has length 3
Assertion failed: *string != '\0', file: CELEBA08 C A1, line: 26 in function analyze