lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Sep 1, 2014, at 11:07 PM, Hao Wu <wuhao.wise@gmail.com> wrote:




With the odd special exception (for example, it’s nearly impossible to write
a decent assert() macro without it).

curious what the use case here is? mind to explain?


—Tim

In non-debug builds, assert() should typically compile to nothing, so it introduces no run-time overhead for non-debug builds. For debug builds, assert(e) should do nothing if e is true, or abort with an error if e is false. However, assert() really needs to be an _expression_ so it can be placed anywhere an _expression_ is expected.

So, how to code assert()? It cannot be an “if” statement, since this is not an _expression_. Enclosing the “if” in braces also fails, since that can cause problems with nested “if” statements and if..else constructs. So you end up with something like this…

#if defined(DEBUG) || defined(_DEBUG)
#define assert(e) ( (void) ((e) ? g_nAssertPassCount++ : (PANIC("assert failed: '" #e "'"), 0)) )
#else
#define assert(e) ( (void) 0 )
#endif

The comma operator here is necessary to discard the result of evaluating the asserted _expression_.

You can do better of course  if the compiler allows inline functions.

—Tim