Krystian S
Krystian S

Reputation: 1616

Initialization of a constexpr variable

[dcl.constexpr] p10 sentence 3 says:

In any constexpr variable declaration, the full-expression of the initialization shall be a constant expression

However, in this declaration:

constexpr int a = 10;
constexpr int b = a;

a is not a constant expression, as it is glvalue core constant expression, but not a permitted result of a constant expression because it does not have static storage duration, and is not a temporary object.

However, with the application of an lvalue-to-rvalue conversion, it will become a constant expression. So does that mean that the initializer does not need to be a constant expression, and only the final result after conversions has to be?

Upvotes: 2

Views: 159

Answers (2)

M.M
M.M

Reputation: 141574

In the link you quoted, see point 10:

A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints:

Your question focused on "permitted result of a constant expression" under the glvalue branch; however in your example it is the other branch "prvalue core constant expression" that applies. This can apply because of [conv.lval]/1,

A glvalue of a non-function, non-array type T can be converted to a prvalue

I agree it is a bit confusing that by "prvalue core constant expression" here they include the case of the result of lvalue-to-rvalue conversion on glvalues that meet the criteria; whereas in some other places in the standard "prvalue" excludes that case.

Upvotes: 3

cpplearner
cpplearner

Reputation: 15868

The word "full-expression" is a defined term. Notably ([intro.execution]/5)

Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.

So yes, since the requirement says "the full-expression of the initialization shall be a constant expression", it means only the full-expression (which includes the conversion), not anything else, is required to be a constant expression.

Upvotes: 1

Related Questions