文章目录
- 前言
- 实现
前言
在 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;
}