本文主要是介绍c++编写自己的assert断言,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 前言
- 实现
前言
在 c + + c++ c++中,assert
只在debug
模式下起作用,为了在release
下也使用,我们可以实现自己的assert
实现
#include<iostream>
#include<cstdlib>bool myAssert(bool expr, const char* file, const char* func, int line)
{if (!expr){std::cerr << "[Assertion failed], "<< "file: " << file <<", "<< "function: "<<func<<","<< "line: " << line<< "." << std::endl;return false;}return true;
}#define MY_ASSERT(expr) myAssert(expr, __FILE__, __FUNCTION__, __LINE__)//#define MY_ASSERT(expr) \
// if (!(expr)) { \
// std::cerr<<"Assertion failed: (" #expr "), function "<<__FUNCTION__ \
// <<", file "<<__FILE__<<", line "<<__LINE__<<"."<<std::endl; \
// return false; \
// }int main()
{int x = 5;if(!MY_ASSERT(x == 5)) return 2;if(!MY_ASSERT(x == 0)) return 3;std::cout << "the line will not be executed if the second assert fails." << std::endl;return 0;
}
这篇关于c++编写自己的assert断言的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!