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 ?
C++ guarantees that variables in a compilation unit (. cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes). But, the order of initialization of variables, is undefined across different compilation units.
A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.
In the initializer list, the order of execution takes place according to the order of declaration of member variables. While using the initializer list for a class in C++, the order of declaration of member variables affects the output of the program. Program 1: C++
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn't need any object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With