Hallo!
I'm looking for a way to add custom messages to assert statements. I found this questions Add custom messages in assert? but the message is static there. I want to do something like this:
assert((0 < x) && (x < 10), std::string("x was ") + myToString(x));
When the assertion fails I want the normal output plus for example "x was 100".
assert(a == b && "A is not equal to B"); Since assert shows the condition that failed, it will display your message too. If it's not enough, you can write your own myAssert function or macro that will display whatever you want.
From a test readability perspective, assertion messages are code comments. Instead of relying on them, refactor tests to be self-documenting. In terms of ease of diagnostics, a better alternative to assertion messages is: Making tests verify a single unit of behavior.
Answer: An assert in C++ is a predefined macro using which we can test certain assumptions that are set in the program. When the conditional expression in an assert statement is set to true, the program continues normally. But when the expression is false, an error message is issued and the program is terminated.
Assertions in C/C++ Following is the syntax for assertion. void assert( int expression ); If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called.
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.
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.
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