Aussie AI
Assert Parameter and Return
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Assert Parameter and Return
An improved solution is an assertion macro that captures the logic “check parameter and return zero” in one place. Such a macro first tests a function parameter and if it fails, the macro will not only emit an assertion failure message, but will also tolerate the error by returning a specified default value from the function.
Here's a generic version for any condition:
#define yassert_and_return(cond,retval) \ if (cond) {} else { \ aussie_yassert_fail(#cond " == NULL", __FILE__, __LINE__); \ return (retval); \ }
The usage of this function is:
float aussie_vector_something(float v[], int n) { yassert_and_return(v != NULL, 0.0f); ... }
The above version works for any condition. Here's another version specifically for testing an incoming function parameter for a NULL value:
#define yassert_param_tolerate_null(var,retval) \ if ((var) != NULL) {} else { \ aussie_yassert_fail(#var " == NULL", __FILE__, __LINE__); \ return (retval); \ }
The usage of this function is:
yassert_param_tolerate_null(v, 0.0f);
If you want to be picky, a slightly better version wraps the “if
-else
” logic
inside a “do
-while(0)
” trick.
This is a well-known trick to make a macro act more function-like
in all statement structures.
#define yassert_param_tolerate_null2(var,retval) \ do { if ((var) != NULL) {} else { \ aussie_yassert_fail(#var " == NULL", __FILE__, __LINE__); \ return (retval); \ }} while(0)
The idea of this macro is to avoid lots of parameter-checking boilerplate
that will be laborious and error-prone.
But it's also an odd style to hide a return
statement inside a function-like preprocessor macro,
so this is not a method that will suit everyone.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |