Explain Constexpr with Const Char*Const [Duplicate]

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?

2

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.

2
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest