当前位置: 技术问答>linux和unix
请解释一下:assert()这个函数,详细点 高分相送
来源: 互联网 发布时间:2015-02-03
本文导语: 请解释一下:assert()这个函数,详细点 高分相送 | assert()函数是判断表达式,如果表达式的结果为FALSE,则打印出诊断信息,并且退出程序。 assert()函数的声明: void assert( int expression ); asse...
请解释一下:assert()这个函数,详细点 高分相送
|
assert()函数是判断表达式,如果表达式的结果为FALSE,则打印出诊断信息,并且退出程序。
assert()函数的声明:
void assert( int expression );
assert()函数的头文件和OS环境:
ANSI, Win 95, Win NT
返回值:
无
参数:
表达式
结果为0或者非0的表达式(包括指针)
备注:
可以使用NDEBUG宏来打开或者关闭assert()函数。
例子:
/* 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
#include
#include
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 != '' ); /* Cannot be empty */
assert( strlen( string ) > 2 ); /* Length must exceed 2 */
}
程序结果输出:
Analyzing string 'abc'
Analyzing string '(null)'
Assertion failed: string != NULL, file assert.c, line 24
abnormal program termination
assert()函数的声明:
void assert( int expression );
assert()函数的头文件和OS环境:
ANSI, Win 95, Win NT
返回值:
无
参数:
表达式
结果为0或者非0的表达式(包括指针)
备注:
可以使用NDEBUG宏来打开或者关闭assert()函数。
例子:
/* 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
#include
#include
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 != '' ); /* Cannot be empty */
assert( strlen( string ) > 2 ); /* Length must exceed 2 */
}
程序结果输出:
Analyzing string 'abc'
Analyzing string '(null)'
Assertion failed: string != NULL, file assert.c, line 24
abnormal program termination