Constant initialization

Sets the initial values of the static variables to a compile-time constant.

# Notes

The compiler is permitted to initialize other staticand thread-local(since C++11) objects using constant initialization, if it can guarantee that the value would be the same as if the standard order of initialization was followed.

Constant initialization usually happens when the program loads into memory, as part of initializing the program’s runtime environment.

# Example

#include <iostream>
#include <array>
 
struct S
{
    static const int c;
};
 
const int d = 10 * S::c; // not a constant expression: S::c has no preceding
                         // initializer, this initialization happens after const
const int S::c = 5;      // constant initialization, guaranteed to happen first
 
int main()
{
    std::cout << "d = " << d << '\n';
    std::array<int, S::c> a1; // OK: S::c is a constant expression
//  std::array<int, d> a2;    // error: d is not a constant expression
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
CWG 441C++98references could not be constant initializedmade constant initializable
CWG 1489C++11it was unclear whether value-initializingan object can be a constant initializationit can
CWG 1747C++11binding a reference to a function could not be constant initializationit can
CWG 1834C++11binding a reference to an xvalue could not be constant initializationit can

# See also