Implementation of the ASSERT macro (C++)

> Coding, hacking, computer graphics, game dev, and such...
User avatar
fips
Site Admin
Posts: 166
Joined: Wed Nov 12, 2008 9:49 pm
Location: Prague
Contact:

Implementation of the ASSERT macro (C++)

Post by fips »

After a long time, I've decided to review some of the basics of my current codebase, namely the ASSERT macro. Browsing the Internet, I'd found 2 good references on this topic (see below) that helped improve my own version of ASSERT, which now looks like this:

Code: Select all

#if defined(FS_ENABLE_ASSERTS)
#   define FS_ASSERT(exp)                                                   \
    do {                                                                    \
        const volatile bool bExp = (exp) ? true : false;                    \
        if(!bExp && fs::aux::AssertHandler(                                 \
         #exp, __FUNCTION__, __FILE__, __LINE__)                            \
        )                                                                   \
        { FS_INVOKE_DEBUG_BREAK; }                                          \
    } while(fs::aux::False())
#else
#   define FS_ASSERT(exp) do { FS_UNUSED(exp); } while(0)
#endif
Here're a few design points I'd like to point out:
  • {} scope ... to protect from dangling else
  • do-while ... to enforce a semicolon
  • volatile, False() ... to disable the 'conditional expression is constant' warning

Code: Select all

#define FS_INVOKE_DEBUG_BREAK { __asm int 3 }
#define FS_UNUSED(exp) do { (void)sizeof(exp); } while(0)

namespace fs { namespace aux {
    bool AssertHandler(const char *, const char *, const char *, int);
    inline bool False() { return false; }
}}
References:
Assert Overview by Joey Hammer
Stupid C++ Tricks: Adventures in Assert by Charles Nicholson
Stupid C++ Tricks: do/while(0) and C4127 by Charles Nicholson