Assert

assert宏的原型定义在< assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:

#include < assert.h>   void assert( int expression );  

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

/* assert example */
#include <stdio.h>
#include <assert.h>

void print_number(int* myInt) {
  assert (myInt!=NULL);
  printf ("%d\n",*myInt);
}

int main ()
{
  int a=10;
  int * b = NULL;
  int * c = NULL;

  b=&a;

  print_number (b);
  print_number (c);

  return 0;
}



In this example, assert is used to abort the program execution if print_number is called with a null pointer as attribute. This happens on the second call to the function, which triggers an assertion failure to signal the bug.

 

使用C++ assert()函数的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。 在调试结束后,可以通过在包含#include < assert.h>的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:

#include < stdio.h>   #define NDEBUG   #include < assert.h> 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值