Aussie AI

Generalized Variable-Value Assertions

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Generalized Variable-Value Assertions

Various generalized assertion macros can not only check values of variables, but also print out the value when the assertion fails. The basic method doesn't print out the variable's value:

    yassert(n == 10);

A better way is:

    yassertieq(n, 10);  // n == 10

The assertion macro looks like:

   #define yassertieq(x,y) \
        (( (x) == (y)) || \
         aussie_yassert_fail_int(#x "==" #y, \
                 (x), "==", (y), \
                __FILE__, __LINE__))

The assertion failure function has extra parameters for the variables and operator string:

    bool aussie_yassert_fail_int(char* str, int x, char *opstr, int y, char* fname, int ln)  
    {
        // Assert failure has occurred...
        g_aussie_assert_failure_count++;
        fprintf(stderr, "AUSSIE INT ASSERT FAILURE: %s, %d %s %d, %s:%d\n", str, x, opstr, y, fname, ln);
        return false;  // Always fails
    }

If you don't mind lots of assertion macros with similar names, then you can define named versions for each operator, such as:

  • yassertneq!=
  • yassertgtr>
  • yassertgeq>=
  • yassertlss<
  • yassertleq<=

If you don't mind ugly syntax, you can generalize this to specify an operator as a parameter:

   yassertiop(n, ==, 10);

The macro with an “op” parameter is:

   #define yassertiop(x, op, y) \
        (( (x) op (y)) || \
         aussie_yassert_fail_int(#x #op #y, \
                 (x), #op, (y), \
                __FILE__, __LINE__))

And finally, you have to duplicate all of this to change from int to float type variables. For example, there's macros named “yassertfeq”, “yassertfop”, and a failure function named “aussie_yassert_fail_float”. There's probably a fancy way to avoid this using C++ templates and compile-time type traits, but only if you're smarter than me.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++