c++ – Is `const constexpr` on Variables Redundant

c++constexprequivalent

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?

Best Answer

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).