Aussie AI

Generalized Assertions

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

Generalized Assertions

Once you've used assertions for a while, you start to hate them a little bit. They start to fail a lot, especially during initial module development and unit testing of new code. And that's the first time they get annoying, because the assertion failure reports don't actually give you enough information to help debug the problem. However, you can set a breakpoint on the assertion failure code, so that's usually good enough.

And the second time that assertions are annoying is when you ship the product. That's when you see assertion failures in the logs as an annoying reminder of your own imperfections. Again, there's often not enough information to reproduce the bug.

So, for your own sanity, and for improved supportability, consider extending your own assertion library into a kind of simplified unit-testing library. The extensions you should consider:

  • Add std::stacktrace capabilities if you can, or use Boost Stacktrace or GCC backtrace as a backup. Printing the whole stacktrace on an assertion failure is a win.
  • Add extra assertion messages as a second argument.
  • Add __func__ to show the function name, if you haven't already.

And you can also generalize assertions to cover some other common code failings.

  • Unreachable code assertion
  • “Null pointer” assertion
  • Integer value assertions
  • Floating-point value assertions
  • Range value assertions

Creating specialized assertion macros for these special cases also means the error messages become more specific.

 

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