ASSERT
评估表达式,当结果为false时,打印诊断信息,并且调用 aborts程序。ASSERT只有在Debug版本中才有效,如果编译为Release版本则被忽略。
#include <assert.h>
void assert(
int expression
);
参数:
expression 对表达式的非零和零的评估。
Example:
在这个程序里, analyze_string函数通过用assert去测试一些条件。如果某个判断条件出错,则这个程序将打印出一条包含错误的信息。
// crt_assert.c
// compile with: /c
#include <stdio.h>
#include <assert.h>
#include <string.h>
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
}
Analyzing string 'abc' Analyzing string '(null)' Assertion failed: string != NULL, file crt_assert.c, line 24