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?
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.
In C++11, constexpr member functions are implicitly const.
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.
The constexpr keyword implies inline.
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
.
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