Often one wants to print out additional information if an assert
fails. A way to do that is this:
assert(vec.size() > i ||
!(std::cerr << "False: " << vec.size() << ">" << i))
This way the actual sizes are printed when the assert
fails. But it's ugly, and also it's easy to forget the !
, which will make the assertion condition true and the program will just continue.
What do people use instead to print additional information on assertion failure, like above?
If an assertion fails, the assert() macro arranges to print a diagnostic message describing the condition that should have been true but was not, and then it kills the program. In C, using assert() looks this: #include <assert. h> int myfunc(int a, double b) { assert(a <= 5 && b >= 17.1); … }
An assertion statement specifies a condition that you expect to be true at a point in your program. If that condition is not true, the assertion fails, execution of your program is interrupted, and the Assertion Failed dialog box appears.
That an “Assert” is used only for validations, where an “If” clause is used for the logic within our code. We can use an “If” clause to determine whether our automation should follow one path or another, but an “Assert” statement to validate the elements within those paths.
Because ASSERT statements are commented out in a release build of an MFC program, the code does not run in a release build.
#define ASSERT(condition) { if(!(condition)){ std::cerr << "ASSERT FAILED: " << #condition << " @ " << __FILE__ << " (" << __LINE__ << ")" << std::endl; } }
Usage:
ASSERT(vec.size()>1);
Result:
ASSERT FAILED: vec.size()>1 @ main.cpp (17)
You can optionally put DebugBreak()
or exit(-1)
or watever into the macro, depending on your needs.
Updated macro with separated left and right side:
#define ASSERT(left,operator,right) { if(!((left) operator (right))){ std::cerr << "ASSERT FAILED: " << #left << #operator << #right << " @ " << __FILE__ << " (" << __LINE__ << "). " << #left << "=" << (left) << "; " << #right << "=" << (right) << std::endl; } }
Usage:
ASSERT(a,>,b);
Result:
ASSERT FAILED: a>b @ assert2.cpp (8). a=3; b=4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With