Bitesize Modern C++ : static_assert

C’s assert library is a useful tool for catching invalid invariants (conditions that must hold true in order for your system to operate as specified) in your program. The big problem with assert is that it’s a run-time check; in many cases the best you can do  to recover from an assert failure is restart the system or put it into a quiescent state.

In a lot of cases the (faulty) invariants could be detected at compile-time but in C++98 there was no mechanism for doing so. The pre-processor has an assert-like mechanism – #error – but the pre-processor has no knowledge of your C++ code so it cannot evaluate program invariants.

In C++11 a compile-time assert mechanism was added: static_assert.

static_assert acts like run-time assert except that the checked-condition must be a constant-expression (that is, an expression that can be evaluated at compile-time); the checked-condition must be a boolean expression, or an expression that can be converted to a boolean.


The message string must be a string literal.  It cannot be a (compile-time) computed value (ignoring pre-processor stringification).

From C++17 the message will be optional.


More information

Can’t wait? Download the full set of articles as a PDF, here.

To learn more about Feabhas’ Modern C++ training courses, click here.

Glennan Carnie
Dislike (0)

About Glennan Carnie

Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry. He specialises in C++, UML, software modelling, Systems Engineering and process development.
This entry was posted in C/C++ Programming and tagged , , , , , . Bookmark the permalink.

2 Responses to Bitesize Modern C++ : static_assert

Leave a Reply