Search code examples
c++initializationglobal-variableslanguage-lawyeroperator-precedence

static global variables initialization order


In many of the answers that I found here were said the following words:

Global variables in a single translation unit (source file) are initialized in the order in which they are defined.

or

Within the same compilation unit the order is well defined: The same order as definition.

etc.

But where can I see these words in the standard of C++? I would like to get a one or few concrete paragraph's where such behavior is described. I can not find it myself, and I do not know who to ask.


Solution

  • 6.6.3 Dynamic initialization of non-local variables [basic.start.dynamic]

    1. Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specialization, and otherwise is ordered. [ Note: An explicitly specialized non-inline static data member or variable template specialization has ordered initialization. — end note ]
    2. Dynamic initialization of non-local variables V and W with static storage duration are ordered as follows:
      • If V and W have ordered initialization and V is defined before W within a single translation unit, the initialization of V is sequenced before the initialization of W.
      • If V has partially-ordered initialization, W does not have unordered initialization, and V is defined before W in every translation unit in which W is defined, then
        • if the program starts a thread (4.7) other than the main thread (6.6.1), the initialization of V strongly happens before the initialization of W;
        • otherwise, the initialization of V is sequenced before the initialization of W.
      • Otherwise, if the program starts a thread other than the main thread before either V or W is initialized, it is unspecified in which threads the initializations of V and W occur; the initializations are unsequenced if they occur in the same thread.
      • Otherwise, the initializations of V and W are indeterminately sequenced.

    Quoted from N4659, formatting adjusted to work with the markdown supported here.

    For the exact definition of dynamic initialization, see the preceding subsesction 6.6.2 [basic.start.static].