Aussie AI
Once-only execution assertion
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Once-only execution assertion
Want to ensure that code is never executed twice?
A function that should only ever be called once?
Here's an idea for an assertion that triggers on the second execution
of a code pathway, by
using its own hidden “static
” call counter local variable:
#define yassert_once() do { \ static int s_count = 0; \ ++s_count; \ if (s_count > 1) { \ aussie_yassert_fail("Code executed twice", \ __FILE__, __LINE__); \ } \ } while(0)
Restricting any block of code to once-only execution is as simple as adding a statement like this:
yassert_once(); // Not twice!
This can be added at the start of a function, or inside any if
statement or else
clause, or
at the top of a loop body (although why is it coded as a loop if you only want it executed once?).
Note that this macro won't detect the case where the code is never executed.
Also note that you could customize this macro to return an error code, or throw a different type of exception,
or other exception handling method when it detects double-executed code.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |