23

I have the following code:

static constexpr const char*const myString = "myString";

Could you please explain what is the difference from:

static const char*const myString = "myString";

What's new we have with constexpr in this case?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
demonplus
  • 5,613
  • 12
  • 49
  • 68
  • 2
    `const` = readonly. `constexpr` = constant. `const` objects can change, `constexpr` objects cannot. Top level `const` cannot change, but functions such as `strlen` cannot tell the difference between regular `const` and top level `const`, hence the need for `constexpr`. – nwp Apr 24 '15 at 10:09
  • 1
    isn't in the first example `static constexpr const char*const` is the same as `static constexpr const char* /*const*/`? https://stackoverflow.com/questions/50609668/is-const-constexpr-on-variables-redundant – dragonxlwang Jan 16 '21 at 19:46

1 Answers1

20

The difference is described in the following quote from the C++ Standard (9.4.2 Static data members)

3 If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignmentexpression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. β€”end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

Consider for example two programs

struct A
{
    const static double x = 1.0;
};

int main() 
{
    return 0;
}

struct A
{
    constexpr static double x = 1.0;
};

int main() 
{
    return 0;
}

The first one will not compile while the second one will compile.

The same is valid for pointers

This program

struct A
{
    static constexpr const char * myString = "myString";
};

int main() 
{
    return 0;
}

will compile while this porgram

struct A
{
    static const char * const myString = "myString";
};

int main() 
{
    return 0;
}

will not compile.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Could you, please, show an example of code to use `myString` which would be correct with one of declarations above and incorrect with the other? – CiaPan Apr 24 '15 at 09:57