c语言中assert的用法

 1 /*************************************************************************
 2     > File Name: assert.c
 3     > Author: Mr.Yang
 4     > Purpose:演示函数assert的用法 
 5     > Created Time: 2017年05月29日 星期一 19时57分54秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 //#define NDEBUG  频繁调用会影响程序的性能,可在调试结束后禁用assert
10 #include <assert.h>//使用assert函数需引入包文件
11 #include <stdlib.h>
12 
13 int main(void)
14 {
15         FILE *fp;
16 
17         /*以写的方式打开*/
18         fp = fopen("test.txt","w");
19         assert(fp);
20         fclose(fp);
21 
22         /*以只读的方式打开*/
23         fp = fopen("newtest.txt","r");//newtest.txt是不存在的
24         assert(fp);
25         fclose(fp);//程序永远都执行不到这里来
26 
27         return 0;
28 }

执行结果:

assert: assert.c:24: main: Assertion `fp' failed.
已放弃

 

函数原型:

#include <assert.h>

void assert( int expression );

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

 

参考来源:http://www.cnblogs.com/ggzss/archive/2011/08/18/2145017.html

 

 

posted @ 2017-05-29 20:23  杨来  阅读(568)  评论(1编辑  收藏  举报