转自:https://www.cnblogs.com/jackluolei/p/8858787.html
assert是常用于程序调试的一个宏函数,在程序运行时,计算assert()括号里面的表达式,如果为false则报错,并且终止程序的运行,相反继续运行。
简而言之:assert()函数的功能是终止程序以免导致更加严重的错误,同时也用于查找错误。
使用assert()函数的情况:
1.在函数开始时检验传入参数的合法性。
2.一个assert()函数一次只能检测一个条件的合法性。
3.因assert()只在DEBUG下生效,故不能使用改变环境的语句。
4.assert()不能用它来实现条件过滤。
5.频繁的调用assert()语句会影响程序的性能,增加额外的开销。
以下转自:https://blog.csdn.net/u011068702/article/details/62037593
1、assert函数介绍
assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include <assert.h>
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
以下为我的理解:
- expression 是一个表达式时,表达式成立为真;不成立时为假。
- expression 是一个数时,数大于0为真;小于等于0时为假。
- expression 是一个指针时,指针的值存在时为真;指针值不存在时为假。
例如:
第1种情况
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int digit = 1;
assert(digit>0);
printf("digit\n");
return 0;
}
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int digit = 1;
assert(digit>3);
printf("digit\n");
return 0;
}
第2种情况
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int digit = 1;
assert(digit);
printf("digit\n");
return 0;
}
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int digit = 0;
assert(digit);
printf("digit\n");
return 0;
}
第3种情况
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char *p;
assert(p);
printf("digit\n");
return 0;
}
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char *p = "abc";
assert(p);
printf("digit\n");
return 0;
}
以下转自:https://blog.csdn.net/kunkliu/article/details/93890641
assert()使用总结:
- 在函数开始阶段,检验传入参数的合法性。
例如:
MsgCpy(msg* dst, msg* src)
{
assert(dst != NULL);
assert(src != NULL);
.......
}
-
每个assert()仅仅检验一个条件。否则出错了不知道是哪个条件出错。
-
不能在assert()中对变量做出改变。因为assert()仅在Debug模式下起作用。若改变了变量,则Release和Debug模式下会有不同。
例如:
assert(i++ < 1024)
则在Debug下,i++被执行了。 Release模式下,i++没被执行。
-
assert()应自成一行,上下有空行。
-
assert()与条件过滤各自有自己的适用点。不能混淆。
还有就是什么时候assert 起作用。如果是默认情况,加了 #include <assert.h>
,assert函数就起作用。有2种方式,可以使release版本,不启用assert。
1、在源文件里,在包含assert.h之前定义一个NDEBUG宏(表示No Debug),就可以禁用assert.h中的assert宏定义。
比如:
#define NDEBUG
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char *p;
assert(p);
printf("digit\n");
return 0;
}
2、源文件中不定义NDEBUG宏。在编译时加上编译选项 -DNDEBUG
,也可以。