Why Q_ASSERT instead of assert

Zitrax picture Zitrax · Aug 8, 2016 · Viewed 15.4k times · Source

In Qt there is a Q_ASSERT macro. What's the advantage of using this instead of assert from <cassert> ?

Answer

Louen picture Louen · Aug 8, 2016

Q_ASSERT is a custom assert macro which supposedly enhances the standard assert function.

The error message is handled by qFatal(), which can behave slightly better on some platforms than the standard assert macro. For example on Windows it will trigger the Visual Studio debugger at the point where the assertion fails instead of just calling abort().

You can also redirect the output of Qt error message functions such as qFatalto your custom message handler ( with qInstallMessageHandler() ). It can be useful for example if you want to redirect the errors message to a file.

Also note that Q_ASSERT is disabled with the macro QT_NO_DEBUG(while assert is disabled by NDEBUG) : this can be used to separate your asserts between Qt-related code and the rest.