Aussie AI
BYO assertion macros
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
BYO assertion macros
An important point about the default “assert” macro is that when the condition fails, the default C++ library crashes your program
by calling the standard “abort” function, which triggers a fatal exception on Windows or a core dump on Linux.
That is fine for debugging, but it isn't what you want for production code,
so most professional C++ programmers declare their own assertion macros instead.
For example, here's my own “yassert” macro in a “yasssert.h” header file:
#define yassert(cond) ( (cond) || aussie_yassert_fail(#cond, __FILE__, __LINE__) )
This tricky macro uses the short-circuiting of the “||” operator,
which has a meaning like “or-else”.
So, think of it this way: the condition is true, or else we call the failure function.
The effect is similar to an if-else statement, but an expression is cleaner in a macro.
The __FILE__ and __LINE__ preprocessor macros expand to the current filename and line number.
The filename is a string constant, whereas the line number is an integer constant.
Function names:
Note that you can add “__func__” to also report the current function name if you wish.
There's also an older non-standard __FUNCTION__ version of the macro.
Note that the need for all these macros goes away once there is widespread C++ support for std::stacktrace,
as standardized in C++23, in which case a failing assertion could simply report its own call stack in an
error message.
When Assertions Fail.
This yassert macro relies on a function that is called only when an assertion has failed.
And the function has to have a dummy return type of “bool” so that it can be used as an operand of the || operator,
whereas a “void” return type would give a compilation error.
Hence, the declaration is:
bool aussie_yassert_fail(char* str, char* fname, int ln); // Assertion failed
And here's the definition of the function:
bool aussie_yassert_fail(char* str, char* fname, int ln)
{
// Assertion failure has occurred...
g_aussie_assert_failure_count++;
fprintf(stderr, "AUSSIE ASSERTION FAILURE: %s, %s:%d\n", str, fname, ln);
return false; // Always fails
}
This assertion failure function must always return “false” so that the assertion macro
can be used in an if-statement condition.
|
• Next: • Up: Table of Contents |
|
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |