C++ 断言

来源:互联网 发布:星际淘宝网txt免费下载 编辑:程序博客网 时间:2024/06/06 04:37

断言是测试某个变量是否具有正确值的有用的调试工具。

assert宏测试时表达式的值

        —如果表达式的值是0(假),则assert打印错误信息,并调用函数abort()以结束程序执行。

—assert宏在assert.h头文件中定义。

断言实例:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include<iostream>  
  2. #include<assert.h>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     int x;  
  8.     cout<<"x:";  
  9.     cin>>x;  
  10.     assert(x < 10);  
  11.     cout<<"x="<<x<<endl;  
  12.     return 0;  
  13. }  

忽略断言

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //忽略断言  
  2. //定义符号常量NDEBUG可忽略后续断言  
  3.   
  4. #define NDEBUG  
  5.   
  6. #include<iostream>  
  7. #include<assert.h>  
  8. using namespace std;  
  9.   
  10. int main()  
  11. {  
  12.     int x;  
  13.     cout<<"x:";  
  14.     cin>>x;  
  15.     assert(x < 10);  
  16.     cout<<"x="<<x<<endl;  
  17.     return 0;  

0 0
原创粉丝点击