Adding message to assert

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.

Leave a Comment