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.
- Practice makes perfect, part 3 – Idiomatic kata - February 27, 2020
- Practice makes perfect, part 2– foundation kata - February 13, 2020
- Practice makes perfect, part 1 – Code kata - January 30, 2020
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.
One correction: the message string must be a string-literal according to C++11, C++14, and the current C++17 draft.
There is a proposal (N4433 to allow it to be a constant-expression that evaluates to a constant C-string type (const char*, const wchar_t*, etc...)
Quite right. I've amended the article to reflect this.
Thanks!