C++ static_assert Keyword
Example
Check a condition when the program is compiled:
const int x = 10;
static_assert(x > 5, "x is too small"); // OK
// static_assert(x > 20, "x is too small"); // Error, because x is not greater than 20
cout << x;
Definition and Usage
The static_assert keyword checks a condition when the program is compiled, before it runs. If the condition is false, the compiler stops and shows your error message.
The condition must be something the compiler can calculate, like a const variable with a fixed value. Always write the error message, because it is required in C++11. Use static_assert to catch mistakes early, for example to check that a constant has a valid value.
Related Pages
Read more about compile-time errors in our C++ Errors Tutorial.
Read more about constants in our C++ Constants Tutorial.