Mehul
Mehul

Reputation: 159

How to write Custom Assert?

We need an application, in release build we need assert and we would like to develop something like XXX_ASSERT but the problem is in MFC ASSERT can take any booleanExpression as an argument and evaluate this but if we write our custom assert e.g. MY_ASSERT than how to achieve that custom assert will evaluate any booleanExpression.

#include<afxwin.h>
#include <stdlib.h>
void abort()
{
    AfxMessageBox(_T("Test"));
}
#define MY_ASSERT(BoolCondition) do { if (!(BoolCondition)) { abort(); } } while (0)
class CAge:public CObject
{
public:
    int m_nAge;
    CAge(int age)
    {
        m_nAge = age;
    }
};
class MyFrame:public CFrameWnd
{
public:
    MyFrame()
    {
        Create(0,_T("Hello"));
    }
    void OnPaint()
    {
        CPaintDC d(this);
        CBrush r;
        r.CreateSolidBrush(RGB(25,200,152));

        d.SelectObject(&r);
        d.Rectangle(100,100,250,250);
        r.DeleteObject();
        CAge *pAge;// = new CAge(21);
        MY_ASSERT(pAge);
    }
    DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(MyFrame, CFrameWnd)
    ON_WM_PAINT()
END_MESSAGE_MAP()
class MyApp:public CWinApp
{
    int InitInstance()
    {
        MyFrame *p = new MyFrame();
        p->ShowWindow(3);
        m_pMainWnd = p;
        return 1;
    }
};
MyApp a;

Upvotes: 1

Views: 1638

Answers (1)

Seg Fault
Seg Fault

Reputation: 1351

The straighforward approach should work just fine for any Boolean expression:

#include <stdlib.h>
#define MY_ASSERT(BoolCondition) do { if (!(BoolCondition)) { abort(); } } while (0)

Upvotes: 4

Related Questions