Reputation: 3672
The below code compiles:
#include <iostream>
int main( )
{
const char* const str = "This is a constant string.";
std::cout << str << '\n';
}
However, this one gives a warning:
constexpr char* const str = "This is a constant string.";
Here:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
37 | constexpr char* const str = "This is a constant string.";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is this a bug in GCC? I'm converting a string to a pointer that is pointing to a constexpr char
array. Is this warning valid?
Now making the pointer itself constexpr
prevents it from being compiled at all:
const char* constexpr str = "This is a constant string.";
Here:
error: expected unqualified-id before 'constexpr'
37 | const char* constexpr str = "This is a constant string.";
| ^~~~~~~~~
Why can't a pointer be constexpr?
Upvotes: 0
Views: 259
Reputation: 2399
Whether or not you are using constexpr here is not the issue. You are trying to store a string literal in a char* const which is not a pointer to immutable data (which the string literal is), but rather a pointer with a constant address. A string literal can be stored as const char* or const char* const instead.
const char* str = "This is a constant string."
Adding constexpr would look like this:
constexpr const char* str = "This is a constant string."
Upvotes: 3