自己 _assertt() 系统函数写的代码如下:
//自己写的 仿 系统的_assert() 函数, 功能不是很完善。
int My_Assert(char* rchar, const char* rLocation, int iLine)
{
cout << "Assert Failed!:" << rchar << " File:" << rLocation << " Line:" << iLine << endl;
exit(1);
}
仿 assert 宏的 代码 如下:
#define my_assert(exp) ((exp) || (My_Assert(#exp, __FILE__, __LINE__)))
测试代码如下:
int main()
{
// 用整形变量测试
int i = 2;
my_assert(i); // i 为 2
cout << i-- << endl;
my_assert(i); // i 为 1
cout << i-- << endl;
my_assert(i); // i 为 0
cout << i-- << endl
// 用 指针变量测试
FILE *fp = NULL;
my_assert(fp); // fp 为 空
return 0;
}
用 整形变量测试 的结果为:
Assert Failed! : i-- File:E:\execise\AssertTest\AssertTest.cpp LIne:54
用 指针变量测试 的结果为:
Assert Failed! : fp File:E:\execise\AssertTest\AssertTest.cpp LIne:59
以下这段是转载自:http://blog.csdn.net/wuxicn/article/details/4774027 的“应该在何时使用assert?”
很多人都拿不准什么时候该使用assert来判断函数的参数是否有效。
例如:一个函数char* f(char* x),是应该 assert(x); 还是:if (x==NULL) return NULL; ?其实到底该用assert还是用if的道理很简单,下面我来说一下。
首先必须明确一点,出于鲁棒性,有些函数参数(如指针)必须得进行检查(用assert或者if)。然后就是该用assert还是用if了?这个得根据函数的定义域来定。例如,有一个求平方根的函数double sqrt(double x);如果用assert(x >= 0); 来进行参数检查,则表明函数的定义域是:[0, +Infinite) ;但如果用if (x < 0) return 0; 来检查,则函数的定义域就是 (-Infinite, +Infinite)了!所以这两函数在逻辑上不是同一个函数。
所以,如果让你实现一个memcpy(dst, src, len)函数,如果是:assert(dst); assert(src); 则表明这个memcpy只能接受非空的指针参数;而如果写成if (dst == NULL) return NULL;则表明,memcpy可以接受空指针参数,只是你要是将空指针作为参数,则返回NULL。
最后还要补充说明一点是,assert只是在DEBUG版本下才有用的,有时候还用作debug时检查一些变量的值。
附:完整代码如下:
#include <iostream>
#include <string>
#include <cstdio>
using std::cout;
using std::endl;
using std::string;
#define my_assert(exp) ((exp) || (My_Assert(#exp, __FILE__, __LINE__)))
//自己写的 仿 系统的_assert() 函数, 功能不是很完善。
int My_Assert(char* rchar, const char* rLocation, int iLine)
{
cout << "Assert Failed!:" << rchar << " File:" << rLocation << " Line:" << iLine << endl;
exit(1);
}
int main()
{
// 用整形变量测试
/*int i = 2;
my_assert(i); // i 为 2
cout << i-- << endl;
my_assert(i); // i 为 1
cout << i-- << endl;
my_assert(i); // i 为 0
cout << i-- << endl;*/
// 用 指针变量测试
FILE *fp = NULL;
my_assert(fp); // fp 为 空
return 0;
}
附: assert 宏在 assert.h 头文件中的声明原型:
#undef assert
#ifdef NDEBUG
#define assert(exp) ((void)0)
#else
#ifdef __cplusplus
extern "C" {
#endif
_CRTIMP void __cdecl _assert(void *, void *, unsigned);
#ifdef __cplusplus
}
#endif
#define assert(exp) (void)( (exp) || (_assert(#exp, __FILE__, __LINE__), 0) )
#endif /* NDEBUG */
以上~~~请大家多多指点~~谢谢!!