Introduced in C++11, static_assert
checks a precondition at compile-time and emits a diagnostic error message.
For any condition that could be checked at compile-time, static_assert
should be preferred to the C macro assert
:
- Because it is checked at compile-time, the maintainer changing the code is immediately warned when the condition breaks, as opposed to
assert
which will trigger only when the specific line is run, potentially by another person.
- Because it is checked at compile-time, it is impossible to accidentally create a side-effect.
- It cannot have a runtime performance cost.
- Contrary to
assert
, it is not a macro and thus doesn’t have the same surprising behaviors like bad handling of commas or confusing
error messages when it doesn’t compile.
- It is designed to emit a customizable error message which will be useful to diagnose the error.
template <class T>
void testFunction(T t) {
assert(sizeof(long) <= sizeof(long long) && "long long is smaller than long!"); // Noncompliant
assert(std::is_integral_v<T> && "This template only works for integral types"); // Noncompliant
assert(t > 0); // Compliant: only known at runtime
// ...
}
template <class T>
void testFunction(T t) {
static_assert(sizeof(long) <= sizeof(long long), "long long is smaller than long!");
static_assert(std::is_integral_v<T>, "This template only works for integral types");
assert(t > 0); // Compliant: only known at runtime
// ...
}
This rule doesn’t trigger for assertions that are false on purpose to stop the execution flow:
[[noreturn]] void stop() {
assert(false); // Compliant: Interrupting the runtime execution
assert(!"We shouldn't reach this"); // Compliant: Interrupting the runtime execution
}