cppreference states that:
A constexpr specifier used in an object declaration or non-static member function (until C++14) implies const.
Does "object declaration" mean "any variable declaration"?
I.e. is
constexpr const int someConstant = 3;
equivalent to
constexpr int someConstant = 3;
in C++11, C++14 and C++17?
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 member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.
Both const and constexpr mean that their values can't be changed after their initialization. So for example: const int x1=10; constexpr int x2=10; x1=20; // ERROR. Variable 'x1' can't be changed.
2) A function defined entirely inside a class/struct/union definition, whether it's a member function or a non-member friend function, is always inline. 3) A function declared constexpr is always inline.
In declarations with primitives, such as the one in your example, const
is indeed redundant. However, there may be odd situations where const
would be required, for example
constexpr int someConstant = 3;
constexpr const int *someConstantPointerToConstant = &someConstant;
Here, someConstantPointerToConstant
is both a constexpr
(i.e. it's known at compile time, hence constexpr
) and it is also a pointer to constant (i.e. its object cannot be changed, hence const
). The second declaration above would not compile with const
omitted (demo).
const
is redundant in const constexpr
for objects.
Does "object declaration" mean "any variable declaration"?
It does.
As per cppreference, a variable or a constant is an object:
A variable is an object or a reference that is not a non-static data member, that is introduced by a declaration.
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