Beware of Q_ASSERT

Sakis Kasampallis | May 12, 2011 min read
I really like the concept of inline assertions. Assertions might be rude, since they kick you out of a program whenever they fail, but by using them you can make sure that your code gives you the expected results. You might argue that Unit Testing is a better approach. I won't say no, but I believe that unit testing is slower to implement and not necessary in all cases.

Anyway this is not where I want to focus. If you are coding in QT, you might be aware of Q_ASSERT. Like other features (QString, QFile, etc.), QT provides its own facility for writing code assertions. So that's another replacement of a standard facility, right? Well, not exactly... What I wasn't aware of, is that Q_ASSERT statements are completely ignored when the application is executing in release mode. They are only taken into account in debug mode. I was using a statement like Q_ASSERT(doThat()) in my code, which was causing a hard to track logical error (since doThat() was never executed in release mode). Luckily, after a couple of hours a colleague of mine discovered the bug.

My mistake: I wrongly assumed that Q_ASSERT acts like the classic assert, which is only ignored in a C++/C program if a special macro (like NDEBUG) is defined. What I actually wanted was my assertions to be checked in both modes, which is done by using the standard assert facility.

So are you using Q_ASSERT? That's fine. Just be aware that Q_ASSERT and assert behave differently.

Happy coding.