Evaluates an expression and, when the result is false, prints a diagnostic message and aborts the program.
void assert(
int expression
);
Parameters:
expression
Expression (including pointers) that evaluates to nonzero or 0.
Example program:
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.
// crt_assert.c
// compile with: /c
#include
#include
#include
void analyze_string( char *string ); // Prototype
int main( void )
{
char test1[] = "abc", *test2 = NULL, test3[] = "";
printf ( "Analyzing string '%s'\n", test1 ); fflush( stdout );
analyze_string( test1 );
printf ( "Analyzing string '%s'\n", test2 ); fflush( stdout );
analyze_string( test2 );
printf ( "Analyzing string '%s'\n", test3 ); fflush( stdout );
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 exceed 2
}
Sample Output
Analyzing string 'abc'
Analyzing string '(null)'
Assertion failed: string != NULL, file crt_assert.c, line 24
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.