Home > Backend Development > C++ > What Happens During Static Initialization Order Fiasco in C ?

What Happens During Static Initialization Order Fiasco in C ?

Patricia Arquette
Release: 2024-12-11 02:05:09
Original
326 people have browsed it

What Happens During Static Initialization Order Fiasco in C  ?

"Static Initialization Order Fiasco" Enigma Unveiled

The infamous "static initialization order fiasco" (SIOF) arises when multiple files within a C program contain static variables that depend on each other for initialization. Consider the following example:

// file1.cpp
extern int y;
int x = y + 1;

// file2.cpp
extern int x;
int y = x + 1;
Copy after login

Questions:

  1. During compilation of file1.cpp, does the compiler:

    • Allocate storage for y?
    • Initialize x?
  2. During compilation of file2.cpp, does the compiler:

    • Allocate storage for x?
    • Initialize y?
  3. When linking file1.o and file2.o, if file2.o is initialized first, does:

    • x receive an initial value of 0?
    • x remain uninitialized?

Answers:

According to the C standard (3.6.2 "Initialization of non-local objects"):

  1. a. The compiler does not allocate storage for y.
    b. The compiler allocates storage for x but does not initialize it.
  2. a. The compiler does not allocate storage for x.
    b. The compiler allocates storage for y but does not initialize it.
  3. a. x receives an initial value of 0.
    b. x does not remain uninitialized.

Explanation:

  • Step 1: x and y are zero-initialized before any other initialization.
  • Step 2: Either x or y is dynamically initialized (standard does not specify which). The initialized variable receives the value 1, as the other variable is zero-initialized.
  • Step 3: The other variable is then dynamically initialized, receiving the value 2.

The above is the detailed content of What Happens During Static Initialization Order Fiasco in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template