Aussie AI

Assertion Failure Extra Message

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

Assertion Failure Extra Message

The typical assertion macro will report a stringized version of the condition argument, plus the source code filename, line number, and function name. This can be a little cryptic, so a more human-friendly extra message is often added. The longstanding hack to do this has been:

    yassert(fp != NULL && "File open failed");   // Works

The trick is that a string constant has a non-null address, so && on a string constant is like doing “and true” (and is hopefully optimized out). This gives the extra message in the assertion failure because the string constant is stringized into the condition (although you'll also see the “&&” and the double quotes, too). Note that an attempt to be tricky with comma operator fails:

    yassert(fp != NULL, "File open failed");   // Bug

There are two problems. Firstly, it doesn't compile because it's not the comma operator, but two arguments to the yassert macro. Even if this worked, or if we wrapped it in double-parentheses, there's a runtime problem: this assertion condition will never fail. The result of the comma operator is the string literal address, which is never false.

Optional Assertion Failure Extra Message: The above hacks motivate us to see if we could allow an optional second parameter to assertions. We need two usages, similar to how “static_assert” currently works in C++:

    yassert(fp != NULL);
    yassert(fp != NULL, "File open failed");

Obviously, we can do this if “yassert” was a function, using basic C++ function default arguments or function overloading. If you have faith in your C++ compiler, just declare the functions “inline” and go get lunch. But if we don't want to call a function just to check a condition, we can also use C++ variadic macros.

 

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++