As the keyword constexpr implies const and it can also be calculated at compile time, does it mean that now declaring variables as const doesn't make sense and we should always declare them as constexpr?
A constexpr variable must be initialized at compile time. All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .
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.
The constexpr function is executed in a context that is evaluated at compile time. This can be a static_assert expression, such as with the type-traits library or the initialization of a C-array.
static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.
and it can also be calculated at compile time, does it mean that now declaring variables as
constdoesn't make sense and we should always declare them asconstexpr?
And must be calculated at compile time (ignoring the as-if rule).
So you can't declare constexpr a variable initialized with a run-time known value. But you can declare it const.
For example: you can't declare bar constexpr
int foo;
std::cin >> foo;
constexpr int bar = foo; // compilation error
but you can declare it const
int foo;
std::cin >> foo;
const int bar = foo; // compile
No, not at all.
constexpr means "constant expression", as in [possibly] statically-known, as in "[possibly] known at compile time".
const means "cannot be changed after initialisation".
These are completely separate concepts. A const object can be initialised with a runtime value, for example.
constexpr can imply const, but const certainly does not imply constexpr.
(I think constexpr is a very confusing name, due to this.)
Adding to @max66 answer: constexpr can only replace a top-level const. It can never replace pointer-to-const or const reference. So, sometimes constexpr and const can be used in the same declaration. E.g.
const char* const s = "Hello";
can be replaced with:
constexpr const char* s = "Hello";
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