No, static_assert()
cannot be used with expressions that are not evaluatable at compile-time. The expression passed to static_assert()
must be a constant expression, meaning it can be evaluated by the compiler during compilation.
For example, this is not allowed:
#include <cassert>
int main() {
int x;
std::cin >> x;
static_assert(x > 0, "x must be positive");
}
error: static_assert expression is not an integral constant expression
For runtime assertions based on user input or values read from files, use regular assert()
or a custom runtime assertion macro instead:
#include <cassert>
#include <iostream>
int main() {
int x;
std::cin >> x;
assert(x > 0 && "x must be positive");
}
Remember, assert()
is typically stripped out in release builds, so you'd need to use a custom always-on assertion for checks you want enabled in release builds.
Some other notes on static_assert
:
static_assert
 is evaluated at compile-time, so it cannot depend on any runtime informationstatic_assert
 does not generate any runtime code or affect program performancestatic_assert
 to validate template parameters, sizes of types, and other invariants that can be checked at compile timeAnswers to questions are automatically generated and may not have been reviewed.
Learn how we can ensure that our application is in a valid state using compile-time and run-time assertions.