Search code examples
c++assert

C++ Assert Message


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.


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).