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>