Implementation of the ASSERT macro (C++)
Posted: Tue Mar 02, 2010 10:22 pm
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:
Here're a few design points I'd like to point out:
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
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
- {} 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; }
}}
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