Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `const constexpr` on variables redundant?

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?

like image 961
Pharap Avatar asked May 30 '18 16:05

Pharap


People also ask

Are constexpr variables const?

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 .

Are constexpr variables inline?

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.

Can constexpr variable be changed?

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.

Is constexpr function always inline?

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.


2 Answers

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

like image 125
Sergey Kalinichenko Avatar answered Sep 20 '22 18:09

Sergey Kalinichenko


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.

like image 42
Maxim Egorushkin Avatar answered Sep 20 '22 18:09

Maxim Egorushkin