Reputation: 25
The project that I have just started working on has many instances of following,
constexpr const char* str = "Some Character(s)";
I wanted to understand, is the "const" keyword in above statement not redundant, as constexpr is implicitly constant?
Upvotes: 0
Views: 66
Reputation: 115
const
and constexpr
has diferent behaivours, as both has the same prefix, you may think that they are the same, but constexpr
means that an atribute (or function, or whatever) will be done in compile time, and const
means that that atribute won't be modified (it is an inmutable value, you can modify it, but thats undefined behaivour), but maybe can't be evaluated at compile time.
Also, in that particular case, you can't create an char *
from an string literal since -std=c++17
Upvotes: 0
Reputation: 4207
It is mandatory because it won't compile if you remove it. This code:
constexpr char *str = "Some Character(s)";
Produces the following error on x64 GCC 11.2 (link):
error: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
1 | constexpr char *str = "Some Character(s)";
| ^~~~~~~~~~~~~~~~~~~
The implied const
is for the pointer itself so a redundant const
would actually be this:
constexpr const char *const str = "Some Character(s)";
// ^~~~~
Upvotes: 1