A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.cppreference.com/w/cpp/language/../named_req/../language/constant_initialization.html below:

Constant initialization - cppreference.com

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

[edit] Explanation

Constant initialization is performed in the following cases:

(until C++11)
  • an lvalue designating an object with static storage duration
  • a temporary object
  • a subobject of a temporary object
  • a function
(since C++11)
(until C++17) (since C++17)
(until C++20) (since C++20)

The effects of constant initialization are the same as the effects of the corresponding initialization, except that it is guaranteed that it is complete before any other initialization of a static or thread-local(since C++11) object begins.

[edit] Notes

The compiler is permitted to initialize other static and 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.

[edit] 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
}

Output:

[edit] 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 441 C++98 references could not be constant initialized made constant initializable CWG 1489 C++11 it was unclear whether value-initializing
an object can be a constant initialization it can CWG 1747 C++11 binding a reference to a function could not be constant initialization it can CWG 1834 C++11 binding a reference to an xvalue could not be constant initialization it can [edit] See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4