|
On Sep 1, 2014, at 11:07 PM, Hao Wu <wuhao.wise@gmail.com> wrote:
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 |