Adding message to assert

前端 未结 8 1615
花落未央
花落未央 2020-12-12 20:36

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 w

8条回答
  •  不知归路
    2020-12-12 21:00

    Extending on Kondrad Rudolph's answer:

    #include 
    
    #ifdef NDEBUG
    #define assert(condition, message) 0
    #else
    #define assert(condition, message)\
       (!(condition)) ?\
          (std::cerr << "Assertion failed: (" << #condition << "), "\
          << "function " << __FUNCTION__\
          << ", file " << __FILE__\
          << ", line " << __LINE__ << "."\
          << std::endl << message << std::endl, abort(), 0) : 1
    #endif
    
    void foo() {
       int sum = 0;
       assert((sum = 1 + 1) == 3, "got sum of " << sum << ", but expected 3");
    }
    
    int main () {
       foo();
    }
    

    Output is...

    Assertion failed: ((sum = 1 + 1) == 3), function foo, file foo.cpp, line 13.
    got sum of 2, but expected 3
    zsh: abort      ./a.out
    

    which is similar to what the std::assert macro outputs on my system just with the additional user defined message

提交回复
热议问题