assert()是一个宏定义,在头文件中<cassert>中,主要用来调试代码用,下面写一个数组下标越界代码测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//梁笔记 //zouzhongliang.com #include <cassert> #include <iostream> #include <string> using namespace std; void FunTest(string& s,int i,char c) { assert(i>=0 && i<s.length()); s[i] = c; } int main() { string s("hello,word"); FunTest(s, 0, '1'); FunTest(s,13,'a'); cout<<s<<endl; return 0; } |
输出结果:
1 |
Assertion failed: i>=0 && i<s.length(), file ..\src\Test_code.cpp, line 11 |
assert断言测试条件为false,FunTest(s,13,’a’);? ?13超过s字符串长度。
使用assert()宏可以有效地发现问题。要取消掉assert()的功能,只要在包含<cassert>头文件之前定义NDEBUG宏。
1 2 |
#define NDEBUG #include <cassert> |
这样就屏蔽掉assert断言功能,一般程式发行版时,都会定义#define NDEBUG
《assert宏运用》上有1条评论
评论已关闭。