Q_ASSERT release build semantics

qdot picture qdot · Sep 24, 2012 · Viewed 8.6k times · Source

I can't find a clear statement on the semantics of Q_ASSERT under release builds. If there is no assertion checking, then is the asserted expression evaluated at all?

Consider the following code

Q_ASSERT(do_something_report_false_if_failed());

Will do_something_report_false_if_failed() run under all potential Qt build configurations? Would it be safer (even though a bit more verbose and less readable) to do this instead:

bool is_ok = do_something_report_false_if_failed();
Q_ASSERT(is_ok)

The latter approach has the downside that ASSERT failures are less verbose, but perhaps it shows more clearly that the statement is executed?

Answer

André Oriani picture André Oriani · Sep 24, 2012

The expression inside the Q_ASSERT will not be evaluated in non-debug build configurations.

Consider the source code below from the Qt repo.

#if !defined(Q_ASSERT)
#  ifndef QT_NO_DEBUG
#    define Q_ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop())
#  else
#    define Q_ASSERT(cond) qt_noop()    
#  endif    
#endif

If QT_NO_DEBUG is defined, then the entire Q_ASSERT statement is replaced with a qt_noop(), thereby removing any expression that it previously contained.

Never rely on any side effects created by an expression inside a Q_ASSERT statement. Technically it is still possible to ensure that QT_NO_DEBUG is not defined in a specific build configuration, but this is not a Good Idea™.