Aussie AI
Assertions for Function Parameter Validation
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Assertions for Function Parameter Validation
Assertions and toleration of exceptions have some tricky overlaps.
Consider the modified version of vector summation with my own “yassert” macro instead:
float vector_sum_assert_example2(float v[], int n)
{
yassert(v != NULL);
float sum = 0;
for (int i = 0; i < n; i++) {
sum += v[i];
}
return sum;
}
This still isn't great in production because it crashes if the assertion fails.
Once control flow returns from the failing “yassert” macro,
then the rest of the code has “v==NULL” and it will immediately crash with a null-pointer dereference.
Hence, the above code works fine only if your “yassert” assertion macro throws an exception. This requires that you have a robust exception handling mechanism in place above it, which is a significant amount of work.
The alternative is to both assert and handle the error in the same place, which makes for a complex block of code:
yassert(v != NULL);
if (v == NULL) {
return 0.0; // Tolerate
}
Slightly more micro-efficient is to only test once:
if (v == NULL) {
yassert(v != NULL); // Always triggers
return 0.0; // Tolerate
}
This is a lot of code that can get repeated all over the place. Various copy-paste coding errors are inevitable.
|
• Next: • Up: Table of Contents |
|
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |