assert() with message

前端 未结 7 705
醉梦人生
醉梦人生 2020-12-24 01:08

I saw somewhere assert used with a message in the following way:

assert((\"message\", condition));

This seems to work great, except that gc

7条回答
  •  执笔经年
    2020-12-24 01:33

    You could write your own macro that provides the same usage of _Static_assert(expr, msg):

    #include 
    #include 
    #include 
    
    
    /*
     * void assert_msg(bool expr, const char *msg);
     */
    #if !defined(NDEBUG)
    #define assert_msg(expr, msg)   do                  \
    {                                                   \
            const bool  e_ = expr;                      \
                                                        \
            if (!e_) {                                  \
                    fputs(msg, stderr);                 \
                    fputc('\n', stderr);                \
                    assert(e_);                         \
            }                                           \
    } while (0)
    #else
    #define assert_msg(expr, msg)   do                  \
    {                                                   \
                                                        \
            if (!(expr))                                \
                    warn_bug(msg);                      \
    } while (0)
    #endif
    

    I also have a macro warn_bug() that prints the name of the program, the file, the line, the function, the errno value and string, and a user message, even if asserts are disabled. The reason behind it is that it won't break the program, but it will warn that a bug will probably be present. You could just define assert_msg to be empty if defined(NDEBUG), though.

提交回复
热议问题