Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr const vs constexpr variables?

It seems obvious that constexpr implies const and thus it is common to see:

constexpr int foo = 42; // no const here 

However if you write:

constexpr char *const str = "foo"; 

Then GCC will spawn "warning: deprecated conversion from string constant to ‘char*’" if -Wwrite-string flag is passed.

Writing:

constexpr const char *const str = "foo"; 

solves the issue.

So are constexpr const and constexpr really the same?

like image 527
Thomas Moulard Avatar asked Mar 04 '15 01:03

Thomas Moulard


People also ask

Should I use constexpr or const?

const applies for variables, and prevents them from being modified in your code. constexpr tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const variables, etc.

Is constexpr implicitly const?

In C++11, constexpr member functions are implicitly const.

Does constexpr improve performance?

In Conclusion. constexpr is an effective tool for ensuring compile-time evaluation of function calls, objects and variables. Compile-time evaluation of expressions often leads to more efficient code and enables the compiler to store the result in the system's ROM.

Does constexpr Impline inline variables?

The constexpr keyword implies inline.


1 Answers

The issue is that in a variable declaration, constexpr always applies the const-ness to the object declared; const on the other hand can apply to a different type, depending on the placement.

Thus

constexpr const int i = 3; constexpr int i = 3; 

are equivalent;

constexpr char* p = nullptr; constexpr char* const p = nullptr; 

are equivalent; both make p a const pointer to char.

constexpr const char* p = nullptr; constexpr const char* const p = nullptr; 

are equivalent. constexpr makes p a const pointer. The const in const char * makes p point to const char.

like image 123
T.C. Avatar answered Oct 12 '22 16:10

T.C.