Errors and Assertions

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?

Abstract art representing computer programming

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

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved