C++ assert with an error message.

c-plus-plus

I forget this one frequently. To write an assert in C++ with an error message, the following works:

assert(a >= b && "a was less than b");

Relevant StackOverflow.

For custom messages – meaning you want to output the values of the variables that cause the assert to fail – there doesn’t seem to be a built-in C++ option. Here’s a function I like, because it uses the assert function from C++, and you replace the contents with a call to your function. At another StackOverflow link.

© Amy Tabb 2018 - 2023. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.