您当前的位置: 首页 >  c++

顺其自然~

暂无认证

  • 0浏览

    0关注

    1317博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ Assert()断言机制原理以及使用

顺其自然~ 发布时间:2021-03-18 08:19:32 ,浏览量:0

MSDN原文如是说:

Evaluates an expression and, when the result is false, prints a diagnostic message and aborts the program.

(判断一个表达式,如果结果为假,输出诊断消息并中止程序。)

void assert( 
   int expression 
);

参数:Expression (including pointers) that evaluates to nonzero or 0.(表达式【包括指针】是非零或零)

原理:assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。

MSDN示例程序;
// 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
}

输出结果

Analyzing string 'abc' Analyzing string '(null)' Assertion failed: string != NULL, file assert.cpp, line 25   abnormal program termination

用法总结:

1)在函数开始处检验传入参数的合法性 如:

int resetBufferSize(int nNewSize)
{
  //功能:改变缓冲区大小,
  //参数:nNewSize 缓冲区新长度
  //返回值:缓冲区当前长度
  //说明:保持原信息内容不变     nNewSize= 0);
  assert(nNewSize =0 && nOffset+nSize= 0);
assert(nOffset+nSize             
关注
打赏
1662339380
查看更多评论
0.0424s