Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain constexpr with const char*const [duplicate]

Tags:

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?

like image 565
demonplus Avatar asked Apr 24 '15 09:04

demonplus


People also ask

What is constexpr const?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

What is constexpr keyword in C++?

constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions. Example: CPP.

What does constexpr constructor mean?

A constructor that is declared with a constexpr specifier is a constexpr constructor. Previously, only expressions of built-in types could be valid constant expressions. With constexpr constructors, objects of user-defined types can be included in valid constant expressions.

What is the difference between const char and char?

Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.


1 Answers

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.

like image 98
Vlad from Moscow Avatar answered Sep 18 '22 16:09

Vlad from Moscow