static initialization order fiasco

前端 未结 4 1203
长发绾君心
长发绾君心 2020-11-22 12:20

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;  
<
4条回答
  •  暖寄归人
    2020-11-22 13:10

    It is compiler dependent and may be runtime dependent. A compiler may decide to lazily initialize static variables when the first variable in a file is accessed, or as each variable is accessed. Otherwise it will initialize all static variables by file at launch time, with the order usually depending on the link order of files. The file order could change based on dependencies or other, compiler dependent influences.

    Static variables are usually initialized to zero unless they have a constant initializer. Again, this is compiler dependent. So one of these variables will probably be zero when the other is initialized. However, since both have initializers some compilers might leave the values undefined.

    I think the most likely scenario would be:

    1. Space is allocated for the variables, and both have the value 0.
    2. One variable, say x, is initialized and set to the value 1.
    3. The other, say y, is initialized and set to the value 2.

    You could always run it and see. It could be that some compilers would generate code that goes into an infinite loop.

提交回复
热议问题