From WikiChip
Difference between revisions of "c/assert.h/assert"
Line 1: | Line 1: | ||
{{DISPLAYTITLE: assert macro - <assert.h> - C}} | {{DISPLAYTITLE: assert macro - <assert.h> - C}} | ||
+ | {{Assert.h - C}} | ||
The '''assert''' macro, which is part of <[[assert.h - C|assert.h]]> can be used to insert diagnostic tests into a program. | The '''assert''' macro, which is part of <[[assert.h - C|assert.h]]> can be used to insert diagnostic tests into a program. | ||
Revision as of 06:00, 1 December 2013
The assert macro, which is part of <assert.h> can be used to insert diagnostic tests into a program.
#include <assert.h>
void assert(scalar expression);
Description
When executed, if the expression is false (I.E. compares to zero), a diagnostic message is printed in an implementation-defined format to the standard error stream. Assert then calls the abort function.
The diagnostic message includes:
- The text of the argument
- The name of the source file (__FILE__)
- The source line number (__LINE__)
- The name of the enclosing function (__func__) (C99)
If NDEBUG is defined as a macro name prior to the inclusion of <assert.h>, assert gets defined as:
#define assert(ignore) ((void)0)
Parameters
Parameter | Description |
---|---|
expression | The expression to be evaluated |
Returns
The assert macro returns no value.
Example
#include <assert.h>
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i++)
{
printf("i = %d\n", i);
assert(i < 5);
}
return 0;
}
Example Output:
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 example: example.c:11: main: Assertion `i < 5' failed. Aborted (core dumped)
Starting at variable i being set to zero, the loop continues until the assertion fails when i reaches 5. The program terminates by calling abort() after printing the diagnostic message.