Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c++ - static initialization order fiasco

I was reading about SIOF from a book and it gave an example :

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

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

Now My question is :
In above code, will following things happen ?

  1. while compiling file1.cpp, compiler leaves y as it is i.e doesn't allocate storage for it.
  2. compiler allocates storage for x, but doesn't initialize it.
  3. While compiling file2.cpp, compiler leaves x as it is i.e doesn't allocate storage for it.
  4. compiler allocates storage for y, but doesn't initialize it.
  5. While linking file1.o and file2.o, now let file2.o is initialized first, so now:
    Does x gets initial value of 0? or doesn't get initialized?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The initialization steps are given in 3.6.2 "Initialization of non-local objects" of the C++ standard:

Step 1: x and y are zero-initialized before any other initialization takes place.

Step 2: x or y is dynamically initialized - which one is unspecified by the standard. That variable will get the value 1 since the other variable will have been zero-initialized.

Step 3: the other variable will be dynamically initialized, getting the value 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...