断言--assert

1. 要点:
(1)assert语句
assert(表达式1); //表达式=0,那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。

示例:

 #include <stdio.h>
 #include <assert.h>
 #include <stdlib.h>


int main( void )
{
    int i = 0;

    assert(i);

    printf("%d\n",i);

    system("pause");
    return 0;   
}

运行结果如下:
这里写图片描述

(2) 断言的添加不能影响本身的代码功能;
(3)assert宏的原型定义在assert.h中。已放弃使用assert()的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。在调试结束后,可以通过在包含的assert.h语句之前插入 #define NDEBUG 来禁用assert调用,如示例2所示。

示例1:

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

示例2:

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

2. 日常用法示例:
鉴于上面对assert语句的描述,在C语言项目工程中,一般通过如下的方式使用断言功能。

#include <stdio.h>
#include <stdlib.h>
//#undef  _EXAM_ASSERT_TEST_    //禁用
#define  _EXAM_ASSERT_TEST_     //启用
#ifdef _EXAM_ASSERT_TEST_       //启用断言测试

void assert_report( const char * file_name, const char * function_name, unsigned int line_no )
{
    printf( "\n[EXAM]Error Report file_name: %s, function_name: %s, line %u\n", 
            file_name, function_name, line_no );
    abort();
}

#define  ASSERT_REPORT( condition )                    \
do{                                                    \
    if ( condition )                                   \
        NULL;                                          \
    else                                               \
        assert_report( __FILE__, __func__, __LINE__ ); \
}while(0)
#else // 禁用断言测试 
#define ASSERT_REPORT( condition )  NULL 
#endif 

int main( void )
{
    int i;
    i=0;

#if 1    
    ASSERT_REPORT(i);
#else   
   i++;
   ASSERT_REPORT(i);
#endif 

    printf("%d\n",i);

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u010603798/article/details/78967687