3

Before asking this, I read previous question, but the issue is a bit different. I'm using this in my class:

static constexpr char* kSuffix = "tos";

Compiling with gcc with c++11 got me this error:

error: ISO C++ forbids converting a string constant to 'char*' [-Werror=write-strings]

But constexpr is a stricter constraint than const does, so a constexpr is must a const, but not vice versa. So I wonder why is gcc not recognising constexpr in this case?

fluter
  • 13,238
  • 8
  • 62
  • 100
  • Does this answer your question? [const constexpr char\* vs. constexpr char\*](https://stackoverflow.com/questions/30561104/const-constexpr-char-vs-constexpr-char) – JaMiT Jan 15 '20 at 05:57
  • Or maybe [constexpr const vs constexpr variables](https://stackoverflow.com/questions/28845058/constexpr-const-vs-constexpr-variables) is a closer fit for a duplicate? – JaMiT Jan 15 '20 at 05:59

1 Answers1

4

so a constexpr is must a const

Note that the constexpr is qualified on kSuffix itself, so the pointer becomes const (as char* const), but the pointee won't become const (as const char*). Gcc just wants to tell you that you should declare kSuffix as a pointer to const, i.e.

static constexpr const char* kSuffix = "tos";
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Is `constexpr` not qualified on `kSuffix`? – fluter Jan 15 '20 at 04:19
  • @fluter Yes. I revised the answer, does it become more clear? – songyuanyao Jan 15 '20 at 04:22
  • I still wonder why `constexpr` take place of `const` here, they are in the same position essentially. – fluter Jan 15 '20 at 05:11
  • @fluter It's better to consider `constexpr` and `const` as different things; e.g. we can declare a `const` pointer like `char* const` and a pointer to `const` like `const char*`, but we can only write `constexpr char*` (or `constexpr const char*`) which means a `constexpr` pointer. (Also note we can't write sth like `char* constexpr`.) – songyuanyao Jan 15 '20 at 05:41