Is declaring variables as const redundant after constexpr was added to the language?
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 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";