Why is the statically initialization of an object definitely zero?

Viewed 113

Consider this example in [basic.start.static#2], which has a more detail interpretation in cppreference

inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;   // unspecified:
                  // dynamically initialized to 0.0 if d1 is dynamically initialized, or
                  // dynamically initialized to 1.0 if d1 is statically initialized, or
                  // statically initialized to 0.0 (because that would be its value
                  // if both variables were dynamically initialized)
double d1 = fd(); // may be initialized statically or dynamically to 1.0

For the first two remarks about dynamic initialization of d2, there is no doubt here. However, it says the static initialization of d2 is 0.0, I cannot figure out the reason. Since the standard didn't specify the order of the static initialization. In other words, If d1 is used to statically initialize d2, why is the value of d1 at this point definitely zero? The standard only says

If constant initialization is not performed, a variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is zero-initialized ([dcl.init]). Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. All static initialization strongly happens before ([intro.races]) any dynamic initialization.

1 Answers

[basic.start.static]/3:

An implementation is permitted to perform the initialization of a variable with static or thread storage duration as a static initialization even if such initialization is not required to be done statically, provided that

  • the dynamic version of the initialization does not change the value of any other object of static or thread storage duration prior to its initialization, and

  • the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

You know that if d1 and d2 are both initialized dynamically, then d1 is initialized to 0, so if d1 is statically initialized, it should be initialized to 0.

Related