Constant expressions

From cppreference.com
< cpp‎ | language
 
 
 
 

Defines an expression that can be evaluated at compile time.

Such expressions can be used as non-type template arguments, array sizes, and in other contexts that require constant expressions, e.g.

int n = 1;
std::array<int, n> a1; // error, n is not a constant expression
const int cn = 2;
std::array<int, cn> a2; // OK, cn is a constant expression

Core constant expressions

A core constant expression is any expression that does not have any one of the following in any subexpression (ignoring unevaluated expressions such as the operand of sizeof or the right operand of builtin && when the left operand evaluates to false)

1) A function call expression that calls a function (or a constructor) that is not declared constexpr
constexpr int n = std::numeric_limits<int>::max(); // OK, max() is constexpr
constexpr int m = std::time(NULL); // Error: std::time() is not constexpr
2) A function call to a constexpr function which is declared, but not defined, or a function call to a constexpr function/constructor template instantiation where the instantiation fails to satisfy constexpr function/constructor requirements.
3) A function call to a constexpr function with arguments that do not produce a constant expression when substituted
constexpr const int* addr(const int& ir) { return &ir; }
static const int x = 5;
constexpr const int* xp = addr(x); // OK
constexpr const int* tp = addr(5); // error: &5 is not a constant expression
4) A function call to a constexpr constructor with arguments that do not produce constant expressions in member-initializer lists that are called from this function
int x;
struct A {
    constexpr A(bool b) : m(b?42:x) { }
    int m;
};
constexpr int v = A(true).m; // OK
constexpr int w = A(false).m; // error: non-const x
5) A function call to a recursive constexpr function that would exceed compile-time recursion depth limit (implementation-defined)
(until C++14)
5) an expression that would exceed the implementation-defined limits
(since C++14)
6) The this pointer, except if used for class member access inside a non-static member function
(until C++14)
6) The this pointer, except in a constexpr function or a constexpr constructor that is being evaluated as part of the expression
(since C++14)
7) An expression whose evaluation leads to any form of core language undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc). Whether standard library undefined behavior is detected is unspecified.
constexpr double d1 = 2.0/1.0; // OK
constexpr double d2 = 2.0/0.0; // Error: not defined
constexpr int n = std::numeric_limits<int>::max() + 1; // Error: overflow
int x, y, z[30];
constexpr auto e1 = &y - &x; // Error: undefined
constexpr auto e2 = &z[20] - &z[3]; // OK
constexpr std::bitset<2> a; 
constexpr bool b = a[2]; // UB, but unspecified if detected
(until C++17)
9) An lvalue-to-rvalue implicit conversion or modification (since C++14) applied to a non-active member of a union or its subobject
10) Any other lvalue-to-rvalue implicit conversion, unless the lvalue...
a) has integral or enumeration type and refers to a complete non-volatile const object, which is initialized with a constant expression
int main() {
    const std::size_t tabsize = 50;
    int tab[tabsize]; // OK: tabsize is a constant expression
 
    std::size_t n = 50;
    const std::size_t sz = n;
    int tab2[sz]; // error: sz is not a constant expression
                  // because sz is not initialized with a constant expression
}
b) is a non-volatile glvalue that refers to an element of a string literal
c) has literal type and refers to a non-volatile object defined with constexpr or to its non-mutable subobject
d) has literal type and refers to a non-volatile temporary object, initialized with a constant expression
(until C++14)
d) has literal type and refers to a non-volatile object whose lifetime began within the evaluation of this expression
(since C++14)
11) an id-expression referring to a variable or a data member of reference type, unless it was initialized with a constant expression or is a non-static data member of a temporary object which was initialized with a constant expression (until C++14)its lifetime began within the evaluation of this expression (since C++14)
12) conversion from cv void* to any pointer-to-object type
(since C++14)
15) pseudo-destructor call
16) an increment or a decrement operator
(until C++14)
16) modification of an object, unless the object has non-volatile literal type and its lifetime began within the evaluation of the expression
constexpr int incr(int& n) {
  return ++n;
}
constexpr int g(int k) {
  constexpr int x = incr(k); // error: incr(k) is not a core constant
                             // expression because lifetime of k
                             // began outside the expression incr(k)
  return x;
}
constexpr int h(int k) {
  int x = incr(k); // OK: x is not required to be initialized with a core
                   // constant expression
  return x;
}
constexpr int y = h(1); // OK: initializes y with the value 2
                        // h(1) is a core constant expression because
                        // the lifetime of k begins inside the expression h(1)
(since C++14)
17) a typeid expression applied to a glvalue of polymorphic type
18) a new-expression or a delete-expression
19) an equality or relational operator when the result is unspecified
20) an assignment or a compound assignment operator
(until C++14)
21) a throw expression
22) inside a lambda-expression, a reference to this or to a variable defined outside that lambda, if that reference would be an odr-use
void g() {
  const int n=0;
  constexpr int j=*&n; // OK, outside of a lambda-expression
  [=]{ constexpr int i=n;  // OK, 'n' is not odr-used and not captured here.
       constexpr int j=*&n;// Ill-formed, '&n' would be an odr-use of 'n'.
     };
}

note that if the ODR-use takes place in a function call to a closure, it does not refer to this or to an enclosing variable, since it accesses a closure's data member instead

// OK: 'v' & 'm' are odr-used but do not occur in a constant-expression
// within the nested lambda
auto monad = [](auto v){return [=]{return v;};};
auto bind = [](auto m){return [=](auto fvm){return fvm(m());};};
// OK to have captures to automatic objects created during constant expression evaluation.
static_assert(bind(monad(2))(monad)() == monad(2)());
(since C++17)

Integral constant expression

Integral constant expression is an expression of integral or unscoped enumeration type implicitly converted to a prvalue, where the converted expression is a core constant expression. If an expression of class type is used where an integral constant expression is expected, the expression is contextually implicitly converted to an integral or unscoped enumeration type.

only integral constant expressions can be used as array bounds, the dimensions in new-expressions other than the first (until C++14), bit-field lengths, enumeration initializers when the underlying type is not fixed, null-pointer constants (until C++14), and alignments.

Converted constant expression

A converted constant expression of type T is an expression implicitly converted to type T, where the converted expression is a constant expression, and the implicit conversion sequence contains only:

  • constexpr user-defined conversions (so a class can be used where integral type is expected)
  • lvalue-to-rvalue conversions
  • integral promotions
  • non-narrowing integral conversions
  • array-to-pointer conversions
  • function-to-pointer conversions
  • function pointer conversions (pointer to noexcept function to pointer to function)
  • qualification conversions
  • null pointer conversions from std::nullptr_t
  • null member pointer conversions from std::nullptr_t
(since C++17)
  • And if any reference binding takes place, it is direct binding (not one that constructs a temporary object)
Only converted constant expressions can be used as case expressions, enumerator initializers when the underlying type is fixed, array bounds, the dimensions in new-expressions other than the first (since C++14), and as integral and enumeration (until C++17)non-type template arguments.

A contextually converted constant expression of type bool is an expression, contextually converted to bool, where the converted expression is a constant expression and the conversion sequence contains only the conversions above. Such expressions can be used in noexcept specifications and static assert declarations.

Literal constant expression

Literal constant expression is a prvalue core constant expression of non-pointer literal type (after conversions as required by context). A literal constant expression of array or class type requires that each subobject is initialized with a constant expression.

Reference constant expression

Reference constant expression is an lvalue core constant expression that designates an object with static storage duration or a function.

Address constant expression

Address constant expression is a prvalue core constant expression (after conversions required by context) of type std::nullptr_t or of a pointer type, which points to an object with static storage duration, one past the end of an array with static storage duration, to a function, or is a null pointer.

Notes

Implementations are not permitted to declare library functions as constexpr unless the standard says the function is constexprcopy elision is mandatory in constant expressions (since C++14)

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 2167 C++14 non-member references local to an evaluation were making the evaluation non-constexpr non-member references allowed
CWG 1313 C++11 undefined behavior was permitted, and all pointer subtraction was prohibited same-array pointer subtraction ok, UB prohibited
CWG 1952 C++11 standard library undefined behavior was required to be diagnosed unspecified whether library UB is diagnosed

See also