Adding message to assert

There are some old tricks to include messages without writing your own routines:

The first is this:

bool testbool = false;
assert(("this is the time", testbool));

There is also:

bool testbool = false;
assert(testbool && "This is a message");

The first one works, because the inside parens expression result is the value of 'testbool'. The second one works, because the value of the string is going to be non-zero.


You are out of luck here. The best way is to define your own assert macro.

Basically, it can look like this:

#ifndef NDEBUG
#   define ASSERT(condition, message) \
    do { \
        if (! (condition)) { \
            std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
                      << " line " << __LINE__ << ": " << message << std::endl; \
            std::terminate(); \
        } \
    } while (false)
#else
#   define ASSERT(condition, message) do { } while (false)
#endif

This will define the ASSERT macro only if the no-debug macro NDEBUG isn’t defined.

Then you’d use it like this:

ASSERT((0 < x) && (x < 10), "x was " << x);

Which is a bit simpler than your usage since you don’t need to stringify "x was " and x explicitly, this is done implicitly by the macro.


A better alternative is to teach the debugger to stop on assert when it fails, then you could examine not only the x value but any other information including call stack. Perhaps, this is what you are really looking for. Sample implementation is mentioned here Ways to show your co-programmers that some methods are not yet implemented in a class when programming in C++