Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print additional information when assert fails?

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?

like image 872
Frank Avatar asked Feb 03 '10 16:02

Frank


People also ask

What happens when an assert statement fails?

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); … }

What happens when assert fails C++?

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.

Under what conditions do we use assert () instead of an if statement?

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.

Does assert work in Release mode?

Because ASSERT statements are commented out in a release build of an MFC program, the code does not run in a release build.


1 Answers

#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
like image 130
Notinlist Avatar answered Sep 22 '22 20:09

Notinlist