assert() — Verify condition
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
Format
#include <assert.h>
void assert(int expression);
General description
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).
Without a compiler
that is designed to support C99, or when compiling C++ code, the diagnostic
message has the following format:
Assertion failed: expression, file filename, line line-number.
With
a compiler that is designed to support C99, or when compiling C++
code, the diagnostic message has the following format:
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.
Note: The
assert() function is a macro. Using the #undef directive
with the assert() macro results in undefined behavior. The assert()
macro uses __FILE__, __LINE__ and,
with a compiler that is designed to support C99, __func__...
Returned value
assert() returns no values.
Example
CELEBA08
/* 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 */
}
Output without a compiler that is designed
to support C99
String1 ABC is not NULL or empty, and has length 3
Assertion failed: *string != '\0', file: CELEBA08 C A1, line: 26
Output
with a compiler that is designed to support C99
String1 ABC is not NULL or empty, and has length 3
Assertion failed: *string != '\0', file: CELEBA08 C A1, line: 26 in function analyze