Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Assertion with Information

📅 2010-Jan-31 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ assertions, cpp, visual cpp ⬩ 📚 Archive

I find it useful to include the comment or information about an assertion in the assert() expression itself.

Code like:

// Check for invalid oxygen level
assert(oxyLevel < OXYGEN_MAX);

can easily be rewritten as:

assert((oxyLevel < OXYGEN_MAX) && "Invalid oxygen levels!!!");

This works because a C string constant is always true (non-zero).

I like the second version since it folds the comment information into the assert() expression. Also, when the assertion fails, Visual Studio pops up a dialog where you can see the entire assert() expression (which includes your informative string):  

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧