一般来说,在程序必须符合一定条件的情况下,才能继续运行,否则就会产生不可预期的错误。 比如除0操作,就可以对被除数(暂命名为iDividend)进行断言: assert( iDividend != 0 ); 一旦iDividend==0,程序就会报错,并自动退出。 MSDN上的代码例题! #include <stdio.h> #include <string.h> #include<assert.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 exceed 2 */ }
Output
Analyzing string 'abc' Analyzing string '(null)' failed: string != NULL, file assert.c, line 24