Aussie AI
Self-Testing Code Block
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Self-Testing Code Block
Sometimes an assertion, unit test, or debug tracing printout is too small to check everything. Then you have to write a bigger chunk of self-testing code. The traditional way to do this in code is to wrap it in a preprocessor macro:
#if YDEBUG
... // block of test code
#endif
Another reason to use a different type of self-testing code than assertions is that you've probably decided to leave the simpler assertions in production code. A simple test like this is probably fine for production:
yassert(ptr != NULL); // Fast
But a bigger amount of arithmetic may be something that's not for production:
yassert(aussie_vector_sum(v, n) == 0.0); // Slow
So, you probably want to have macros and preprocessor settings for both production and debug-only assertions and self-testing code blocks. The simple way looks like this:
#if YDEBUG
yassert(aussie_vector_sum(v, n) == 0.0);
#endif
Or you could have your own debug-only version of assertions that are skipped for production mode:
yassert_debug(aussie_vector_sum(v, n) == 0.0);
The definition of “yassert_debug” then looks like this in the header file:
#if YDEBUG
#define yassert_debug(cond) yassert(cond) // Debug mode
#else
#define yassert_debug(cond) // nothing in production
#endif
This makes the “yassert_debug” macro a normal assertion in debug mode,
but the whole coded expression disappears to nothing in production build mode.
The above example assumes a separate set of build flags for a production build.
|
• Next: • Up: Table of Contents |
|
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |