Print a diagnostic message and optionally terminate the program
#include <assert.h> void assert( int expression );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The assert() macro prints a diagnostic message on the stderr stream, and terminates the program, using abort(), if expression is false (0).
The diagnostic message includes the expression, the name of the source file (the value of __FILE__) and the line number of the failed assertion (the value of __LINE__).
No action is taken if expression is true (nonzero).
You typically use the assert() macro while developing a program, to identify program logic errors. You should choose the expression so that it's true when the program is functioning as intended.
After the program has been debugged, you can use the special “no debug” identifier, NDEBUG, to remove calls to assert() from the program when it's recompiled. If you use the -D option to qcc or a #define directive to define NDEBUG (with any value), the C preprocessor ignores all assert() calls in the program source.
To remove the calls to assert(), you must define
NDEBUG in the code before including the
<assert.h> header file (i.e.
#include <assert.h>).
If you define NDEBUG, the preprocessor also ignores the expression you pass to assert(). For example, if your code includes: assert((fd = open("filename", O_RDWR)) != -1); and you define NDEBUG, the preprocessor ignores the entire call to assert(), including the call to open(). |
#include <stdio.h> #include <stdlib.h> #include <assert.h> void process_string( char *string ) { /* use assert to check argument */ assert( string != NULL ); assert( *string != '\0' ); /* rest of code follows here */ } int main( void ) { process_string( "hello" ); process_string( "" ); return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
assert() is a macro.