Prints an error message and aborts the program.
#include <assert.h>
#include <stdio.h>
void assert(intexpression );
expression | C expression specifying assertion being tested |
The assert routine prints a diagnostic message and calls the abort routine if expression is false (0). The diagnostic message has the form
Assertion failed: expression, file filename, line linenumber
where filename is the name of the source file and linenumber is the line number of the assertion that failed in the source file. No action is taken if expression is true (nonzero).
In Windows, the diagnostic message appears in an “Assertion Failed” pop-up window.
The assert routine is typically used in program development to identify program logic errors. The given expression should be chosen so that it holds true only if the program is operating as intended. After a program has been debugged, the special “no debug” identifier NDEBUG can be used to remove assert calls from the program. If NDEBUG is defined (by any value) with a /D command-line option or with a #define directive, the C preprocessor removes all assert calls from the program source.
The assert routine is implemented as a macro.
None.
Standards:ANSI, UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
/* ASSERT.C: In this program, the analyze_string function uses the
* assert function to test several conditions related to string and
* length. If any of the conditions fails, the program prints a
* message indicating what caused the failure.
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
void analyze_string( char *string ); /* Prototype */
void main( void )
{
char test1[] = "abc", *test2 = NULL, test3[] = "";
printf ( "Analyzing string '%s'\n", test1 );
analyze_string( test1 );
printf ( "Analyzing string '%s'\n", test2 );
analyze_string( test2 );
printf ( "Analyzing string '%s'\n", test3 );
analyze_string( test3 );
}
/* Tests a string to see if it is NULL, empty, or longer than 0 characters */
void analyze_string( char * string )
{
assert( string != NULL ); /* Cannot be NULL */
assert( *string != '\0' ); /* Cannot be empty */
assert( strlen( string ) > 2 ); /* Length must be greater than 2 */
}
Analyzing string 'abc'
Analyzing string '(null)'
Assertion failed: string != NULL, file assert.c, line 28
abnormal program termination