Question

Im really quickly trying to figure out what the "custom message" of an assert does. I can't seem to find the answer.

ie:

int x = -1; 
assert (x > 0 && "Number must be above 0");

Where does the message actually output? Because it sure isn't being displayed when I try it.

Was it helpful?

Solution

Since assert typically is implemented something like this (probably a whole lot more complex, but simplified here)

#define assert(x) if (!(x)) { assert_fail(#x, __FILE__, __LINE__); }

void assert_fail(const char *str, const char *file, int line)
{
  std::cerr << "Assertion failed " << str << " " << file << ":" << line << std::endl;
  abort();
}

then adding && "Some string" to the condition will make assert print the message as well. Which is quite handy for identifying WHY it went wrong. I use this exact pattern in my code.

Of course, some assert implementations don't print the condition that failed, in which case you won't see the string. You could fix this by replacing the existing assert with my_assert and using something like the above.

It also comes in handy if you are running your code in a debugger (e.g. in an IDE) where the string will be shown together with the condition when the debugger stops due to an assert (it may well stop somewhere deeper inside the code, but if you step back up the call-stack, it will eventually get to the point where the assert is, and you can see what the message is).

OTHER TIPS

It doesn't output anything by itself, but allows us to see the string on inspection. Basically, since a string is true as an expression, we can tag it on to any assertion and it will be there when the other part of the expression fails.

So in the case where assert prints to stderr, which many implementations do, the output will be something akin to Assertion 'x > 0 && "Number must be above 0"', this will be the case in most circumstances on unix platforms.

In the case where NDEBUG is defined, it will simply be a no-op and preprocessed away.

Assert messages are used when you are sure that a variable in your program will always have some defined value/range of values and if it takes any other value, it should indicate an error in your code which will make your program crash and it will print the assert message.

In your case, when I run your code, I get:

a.out: del.c:7: main: Assertion `x > 0 && "Number must be above 0"' failed.
Aborted (core dumped)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top