Add custom messages in assert?

后端 未结 8 1017
心在旅途
心在旅途 2020-12-04 07:18

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

8条回答
  •  情话喂你
    2020-12-04 07:40

    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.

提交回复
热议问题