Namespaces
Variants
Actions

constexpr specifier (since C++11)

From cppreference.com
< cpp‎ | language
 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Contents

[edit] Explanation

The constexpr specifier declares that it is possible to evaluate the value of the entities at compile time. Such entities can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).

A constexpr specifier used in an object declaration or non-static member function(until C++14) implies const.

A constexpr specifier used in the first declaration of a function or static data member(since C++17) implies inline. If any declaration of a function or function template has a constexpr specifier, then every declaration must contain that specifier.

[edit] constexpr variable

A variable or variable template(since C++14) can be declared constexpr if all following conditions are satisfied:

(until C++26)
(since C++26)

  • It has constant destruction, which means one of the following conditions needs to be satisfied:
  • It is not of class type nor (possibly multi-dimensional) array thereof.
  • It is of a class type with a constexpr destructor or (possibly multi-dimensional) array thereof, and for a hypothetical expression e whose only effect is to destroy the object, e would be a core constant expression if the lifetime of the object and its non-mutable subobjects (but not its mutable subobjects) were considered to start within e.

If a constexpr variable is not translation-unit-local, it should not be initialized to refer to a translation-unit-local entity that is usable in constant expressions, nor have a subobject that refers to such an entity. Such initialization is disallowed in a module interface unit (outside its private module fragment, if any) or a module partition, and is deprecated in any other context.

(since C++20)

[edit] constexpr function

A function or function template can be declared constexpr.

A function is constexpr-suitable if all following conditions are satisfied:

  • If it is a constructor or destructor(since C++20), its class does not have any virtual base class.
(until C++20)
  • Its return type (if exists) is a literal type.
  • Each of its parameter types is a literal type.
(until C++23)
(since C++20)
  • Its function body is = default, = delete, or a compound statement enclosing only the following:
(until C++14)
  • Its function body is = default, = delete, or a compound statement that(until C++20) does not enclose the following:
  • goto statements
  • statements with labels other than case and default
(until C++20)
  • definitions of variables of non-literal types
  • definitions of variables of static or thread storage duration
(since C++14)
(until C++23)

Except for instantiated constexpr functions, non-templated constexpr functions must be constexpr-suitable.

For a non-constructor constexpr function that is neither defaulted nor templated, if no argument values exist such that an invocation of the function could be an evaluated subexpression of a core constant expression, the program is ill-formed, no diagnostic required.

For a templated constexpr function, if no specialization of the function/class template would make the templated function constexpr-suitable when considered as a non-templated function, the program is ill-formed, no diagnostic required.

(until C++23)

An invocation of a constexpr function in a given context produces the same result as an invocation of an equivalent non-constexpr function in the same context in all respects, with the following exceptions:

[edit] constexpr constructor

On top of the requirements of constexpr functions, a constructor also needs to satisfy all following conditions to be constexpr-suitable:

  • Its function body is = delete or satisfies the following additional requirements:
  • If the class is a union having variant members, exactly one of them is initialized.
  • If the class is a union-like class, but is not a union, for each of its anonymous union members having variant members, exactly one of them is initialized.
  • Every non-variant non-static data member and base class subobject is initialized.
(until C++20)
  • If the constructor is a delegating constructor, the target constructor is a constexpr constructor.
  • If the constructor is a non-delegating constructor, every constructor selected to initialize non-static data members and base class subobjects is a constexpr constructor.
(until C++23)

For a constexpr constructor that is neither defaulted nor templated, if no argument values exist such that an invocation of the function could be an evaluated subexpression of the initialization full-expression of some object subject to constant expression, the program is ill-formed, no diagnostic required.

(until C++23)

[edit] constexpr destructor

Destructors cannot be constexpr, but a trivial destructor can be implicitly called in constant expressions.

(until C++20)

On top of the requirements of constexpr functions, a destructor also needs to satisfy all following conditions to be constexpr-suitable:

  • For every subobject of class type or (possibly multi-dimensional) array thereof, that class type has a constexpr destructor.
(until C++23)
  • The class does not have any virtual base class.
(since C++20)

[edit] Notes

Because the noexcept operator always returns true for a constant expression, it can be used to check if a particular invocation of a constexpr function takes the constant expression branch:

constexpr int f(); 
constexpr bool b1 = noexcept(f()); // false, undefined constexpr function
constexpr int f() { return 0; }
constexpr bool b2 = noexcept(f()); // true, f() is a constant expression
(until C++17)

It is possible to write a constexpr function whose invocation can never satisfy the requirements of a core constant expression:

void f(int& i) // not a constexpr function
{
    i = 0;
}
 
constexpr void g(int& i) // well-formed since C++23
{
    f(i); // unconditionally calls f, cannot be a constant expression
}
(since C++23)

Constexpr constructors are permitted for classes that are not literal types. For example, the default constructor of std::shared_ptr is constexpr, allowing constant initialization.

Reference variables can be declared constexpr (their initializers have to be reference constant expressions):

static constexpr int const& x = 42; // constexpr reference to a const int object
                                    // (the object has static storage duration
                                    //  due to life extension by a static reference)

Even though try blocks and inline assembly are allowed in constexpr functions, throwing exceptions that are uncaught(since C++26) or executing the assembly is still disallowed in a constant expression.

If a variable has constant destruction, there is no need to generate machine code in order to call destructor for it, even if its destructor is not trivial.

A non-lambda, non-special-member, and non-templated constexpr function cannot implicitly become an immediate function. Users need to explicitly mark it consteval to make such an intended function definition well-formed.

(since C++20)
Feature-test macro Value Std Feature
__cpp_constexpr 200704L (C++11) constexpr
201304L (C++14) Relaxed constexpr, non-const constexpr methods
201603L (C++17) Constexpr lambda
201907L (C++20) Trivial default initialization and asm-declaration in constexpr functions
202002L (C++20) Changing the active member of a union in constant evaluation
202110L (C++23) Non-literal variables, labels, and goto statements in constexpr functions
202207L (C++23) Relaxing some constexpr restrictions
202211L (C++23) Permitting static constexpr variables in constexpr functions
202306L (C++26) Constexpr cast from void*: towards constexpr type-erasure
__cpp_constexpr_in_decltype 201711L (C++11)
(DR)
Generation of function and variable definitions when needed for constant evaluation
__cpp_constexpr_dynamic_alloc 201907L (C++20) Operations for dynamic storage duration in constexpr functions

[edit] Keywords

constexpr

[edit] Example

Defines C++11/14 constexpr functions that compute factorials; defines a literal type that extends string literals:

#include <iostream>
#include <stdexcept>
 
// C++11 constexpr functions use recursion rather than iteration
constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n - 1));
}
 
// C++14 constexpr functions may use local variables and loops
#if __cplusplus >= 201402L
constexpr int factorial_cxx14(int n)
{
    int res = 1;
    while (n > 1)
        res *= n--;
    return res;
}
#endif // C++14
 
// A literal class
class conststr
{
    const char* p;
    std::size_t sz;
public:
    template<