5

如何使用C语言的assert断言?

 3 years ago
source link: https://www.maixj.net/ict/assert-24262
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何使用C语言的assert断言?

2020年12月29日 / 3次阅读CC++

调试程序的有效手段,就是加断言,assert。

“断言”在语文中的意思是“断定”、“十分肯定地说”,在编程中是指对某种假设条件进行检测,如果条件成立就不进行任何操作,如果条件不成立就捕捉到这种错误,并打印出错误信息,终止程序执行。

C语言的assert函数,定义在 assert.h 头文件中。

在C代码中出现大量断言,不会影响可读性。我以前很少用assert,现在要调整一下了。使用assert有的时候可以很方便的发现程序的错误。

代码中的assert调用,不需要在调试完毕之后去掉,可以一直保留。

只需要在gcc编译的时候,命令行增加 -DNDEBUG 宏(请参考gcc常用编译参数),assert调用就自动被 ((void)0)空语句替换。因此,也不会影响最终代码的性能。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK