file1.cpp
#include <iostream>
extern int u;
int i=9;
int j=i+9;
int main()
{
std::cout<<u;
return 0;
}
file2.cpp
extern int j;
int u=j+9;
Result is u=9 but not 27
This shows that j is initialized twice – First zero(due to which variable u get value 9) and then with 18
Is it possible ?? My meaning for initialization is destroyed here.
I also try to make variable j constant to see what will happen next
file1.cpp //after changing j to constant
extern int u;
int i=9;
extern const int j=i+9;
This has same output as before.
However if I change int j=i+9;(in file1.cpp) to int j=9;
Surprisingly, I got correct values i.e. u=18;
The order of initialization of global variables declares across different translation Units is not specified.
The globals
uandi,jreside in different translation units in your code, so the order whetherugets initialized first ori&jget initialized beforeuis Unspecified.This invokes an Undefined Behavior in your code.This invokes an Unspecified Behavior in your code
However, Note that order of initialization of globals in the same translation unit is well-defined.
i.e: it is well defined that
iwill be initialized beforejin your code.What you are seeing is a classic case of Static Initialization Fiasco.