大宇私人领地伊甸园丨宁愿做了后悔,也不要错过后悔[www.mrdayu.com]
注册

24小时联系邮箱:[email protected]

所有文章
大宇私人伊甸园: 首页 > 所有文章 > 编程人生 > C/C++语言 > C标准库详解 > assert函数详解


友情链接:


assert函数详解

发布时间:2018/12/06 C标准库详解 标签assert阅读:21

函数使用:

assert(a != 1);

说明:

This is a macro that implements a runtime assertion,

which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false.

当运行时:

if the expression is false (that is, compares equal to 0), assert() will write information about the call that failed on stderr and then call abort().

The information it writes to stderr includes:

  • the source filename (the predefined macro __FILE__)
  • the source line number (the predefined macro __LINE__)
  • the source function (the predefined identifier __func__) (added in C99)
  • the text of expression that evaluated to 0

Linux平台测试:

#include <stdio.h>
#include <assert.h>
int main(){
        int i=0;
        assert(i!=0);
        return 0;
}

运行:

[[email protected] STDC]$ gcc stdc_assert.c
[[email protected] STDC]$ ./a.out 
a.out: stdc_assert.c:5: main: Assertion `i!=0' failed.
Aborted (core dumped)

Windows平台测试:

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

int test_assert(int x)
{
	assert(x <= 4);
	return x;
}
int main()
{
	int i;

	for (i = 0; i <= 9; i++)
	{
		test_assert(i);
		printf("i = %d\n", i);
	}
	return 0;
}

运行结果:

Assert源码:

/* _Assert function */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void _Assert(char *mesg)
	{	/* print assertion message and abort */
	fputs(mesg, stderr);
	fputs(" -- assertion failed\n", stderr);
	abort();
	}
The bottom line, for me, is simple.

Let’s hope it doesn’t take 500 years for a discipline of testing to becomes the standard for software developers.

From:dayu

您好!请登录

合作网站快捷登录:
点击取消回复

已有1评论

    大宇博客

    点击这里给我发消息 点击这里给我发消息 点击这里给我发消息 点击这里给我发消息