"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:
-
During compilation of file1.cpp, does the compiler:
- Allocate storage for y?
- Initialize x?
-
During compilation of file2.cpp, does the compiler:
- Allocate storage for x?
- Initialize y?
-
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"):
-
a. The compiler does not allocate storage for y.
b. The compiler allocates storage for x but does not initialize it.
-
a. The compiler does not allocate storage for x.
b. The compiler allocates storage for y but does not initialize it.
-
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!