Using static_assert with Non-constexpr Expressions

Can static_assert() be used with expressions that are not known at compile-time, such as values read from a file or user input?

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:

  • The expression must be a boolean constant expression, not just any constant expression
  • static_assert is evaluated at compile-time, so it cannot depend on any runtime information
  • static_assert does not generate any runtime code or affect program performance
  • Use static_assert to validate template parameters, sizes of types, and other invariants that can be checked at compile time

Errors and Assertions

Learn how we can ensure that our application is in a valid state using compile-time and run-time assertions.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using Assert in Release Builds
The lesson mentions that assert() calls are sometimes stripped out in release builds for performance. What if I want to keep some critical assertions enabled in release builds?
Avoiding Side Effects in Assertions
Is it okay to use assert() with expressions that have side effects, like assert(++x > 0)? Or should assertions be side-effect free?
Assertions vs Exceptions
When should I use assertions vs throwing exceptions? They seem to serve similar purposes.
Defensive Programming with Assertions
How can I use assertions to practice "defensive programming" and make my code more robust?
Using static_assert in Template Code
The lesson shows an example of using static_assert() with std::is_floating_point to validate template parameters. What are some other common type traits I can use for template validation?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant