I understand that a constexpr
variable can be used at compiletime.
For a template, or static asser for instance.
But if I want to do that without constexpr I can with static const
.
What is since C++11/14 introduced constexpr the difference between
constexpr int a = 3;
//AND
static const int a = 3;
Thank you!
Another way to see this question is which should I use?
The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time.
constexpr variable is guaranteed to have a value available at compile time. whereas static const members or const variable could either mean a compile time value or a runtime value. Typing constexpr express your intent of a compile time value in a much more explicit way than const .
Static specifies the lifetime of the variable. A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later.
constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.
The main difference that I know is, the value of constexpr
must be known in compile-time while a const static
can be assigned in run-time.
const static int x = rand();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With