Add custom messages in assert?

2019-01-12 22:28发布

Is there a way to add or edit the message thrown by assert? I'd like to use something like

assert(a == b, "A must be equal to B");

Then, the compiler adds line, time and so on...

Is it possible?

标签: c++ assert
8条回答
甜甜的少女心
2楼-- · 2019-01-12 22:32

A hack I've seen around is to use the && operator. Since a pointer "is true" if it's non-null, you can do the following without altering the condition:

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.

查看更多
Melony?
3楼-- · 2019-01-12 22:37

Another option is to reverse the operands and use the comma operator. You need extra parentheses so the comma isn't treated as a delimiter between the arguments:

assert(("A must be equal to B", a == b));

(this was copied from above comments, for better visibility)

查看更多
Root(大扎)
4楼-- · 2019-01-12 22:39

Here's my version of assert macro, which accepts the message and prints everything out in a clear way:

#include <iostream>

#ifndef NDEBUG
#   define M_Assert(Expr, Msg) \
    __M_Assert(#Expr, Expr, __FILE__, __LINE__, Msg)
#else
#   define M_Assert(Expr, Msg) ;
#endif

void __M_Assert(const char* expr_str, bool expr, const char* file, int line, const char* msg)
{
    if (!expr)
    {
        std::cerr << "Assert failed:\t" << msg << "\n"
            << "Expected:\t" << expr_str << "\n"
            << "Source:\t\t" << file << ", line " << line << "\n";
        abort();
    }
}

Now, you can use this

M_Assert(ptr != nullptr, "MyFunction: requires non-null argument");

And in case of failure you will get a message like this:

Assert failed:  MyFunction: requires non-null argument

Expected: ptr != nullptr

Source: C:\MyProject\src.cpp, line 22

Nice and clean, feel free to use it in your code =)

查看更多
SAY GOODBYE
5楼-- · 2019-01-12 22:43

Why nobody mentioned the cleanest solution?

bool AMustBeEqualToB = (a == b);
assert(AMustBeEqualToB);
查看更多
一夜七次
6楼-- · 2019-01-12 22:44

For vc, add following code in assert.h,

#define assert2(_Expression, _Msg) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Msg), _CRT_WIDE(__FILE__), __LINE__), 0) )
查看更多
Animai°情兽
7楼-- · 2019-01-12 22:45

assert is a macro/function combination. you can define your own macro/function, using __FILE__, __BASE_FILE__, __LINE__ etc, with your own function that takes a custom message

查看更多
登录 后发表回答