Aussie AI
Assertion Return Value Usage
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Assertion Return Value Usage
Some programmers like to use an assertion style that tests the return code
of their assert
macro:
if (assert(ptr != NULL)) { // Risky // Normal code ptr->count++; } else { // Assertion failed }
This assertion style can be used if you like it, but I don't particularly recommend it, because it has a few risks:
1. The hidden assert failure function must return “false
” so that “if
” test fails when the assertion fails.
2. Embedding assertions deeply into the main code expressions increases the temptation to use side effects like “++
” in the condition,
which can quietly disappear if you ever remove the assertions from a production build:
if (assert(++i >= 0)) // Risky
3. The usual assertion removal method of “((void)0)” will fail with compilation errors in an if statement. Also using a dummy replacement value of “0” is incorrect, and even “1” is not a great option, since the “if(assert(ptr!=NULL))” test becomes the unsafe “if(1)”. A safer removal method is a macro:
#define assert(cond) (cond)
Or you can use an inline
function:
inline void assert(bool cond) { } // Empty
This avoids crashes, but may still leave debug code running (i.e. a slug, not a bug).
It relies on the optimizer to remove any assertions that are not inside an “if
” condition,
which just leave a null-effect condition sitting there.
Note also that this removal method with “(cond)
” is also safer because keeping the condition also retains any side-effects in that condition (i.e. the optimizer won't remove those!).
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |