How to print additional information when assert fails?

assert, c++, debugging

Solution

#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

Problem

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?

Original source

Related problems