23

I know the difference between const and constexpr. One is a compile time constant and the other is either compile time or runtime constant.

However, for array of chars/strings, I'm confused why the compiler complains about one being used over the other.

For example I have:

constexpr char* A[2] = {"....", "....."};

const constexpr char* B[2] = {"....", "....."};

With declaration "A" I get:

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

but with declaration "B" I get no warnings.

Why does the extra const qualifier get rid of the warning? Aren't both of them "const char*" anyway? I ask because both are declared with constexpr which should make it a const char* by default?

I'd expect A to be fine :S

2
  • 10
    constexpr applies to the pointer, making it const, but not the object that it points to. So this is one of a few cases where you might need to combine const and constexpr.
    – David G
    May 31, 2015 at 18:33
  • 8
    constexpr char* is a char* const. The constexpr specifier applies to the whole type of the object -that is, it applies to the declaration-, const is a qualifier (of a type).
    – dyp
    May 31, 2015 at 18:34

1 Answer 1

16

const tells the compiler that the chars you are pointing to should not be written to.

constexpr tells the compiler that the pointers you are storing in those arrays can be totally evaluated at compile time. However, it doesn't say whether the chars that the pointers are pointing to might change.

By the way, another way you could write this code would be:

const char * const B[2];

The first const applies to the chars, and the second const applied to the array itself and the pointers it contains.

1
  • 1
    I would recommend writing char const * const B[2]; since you can read it right-to-left with proper meaning: A constant pointer to a constant char.
    – user904963
    Nov 30, 2021 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.