曲径通幽论坛

标题: assert [打印本页]

作者: beyes    时间: 2009-5-28 22:12
标题: assert

#include <assert.h>

void assert( int exp );
功能: assert()用于错误检测。如果表达式的结果为零,宏写错误信息到STDERR并退出程序执行。如果宏NDEBUG已经定义,宏assert()将被忽略。

测试代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <assert.h>

int main()
{
    int fd;

    fd = open ("test.txt", O_RDONLY);
   
    assert (fd > 0);

    printf ("test.txt can be open\n");

    return (0);
}
说明
这里已经事先知道 test.txt 在当前目录下不存在,所以无法打开,fd 为 -1。在 assert() 函数里,它的要求是 fd > 0 程序才能往下走,否则出错退出,而且还会提示出错的行数。中文 linux 环境下运行此程序运行输出为:
./assert
assert: assert.c:13: main: Assertion `fd > 0' failed.
已放弃






欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2