(Beginner Question:)
I initialized some global variables via user defined functions, and compared their execution sequence with main(). Result shows that these global variables' initialization come first.
I am not sure whether there is any execution sequence outside main function. May I confirm this is always the case (that global declarative region comes before main()
)?
It is confusing to see that c
being declared after main()
but executed earlier.
Below is the code I used:
int foo(string);
int a = foo("a"); /* global var init */
int main(int argc, char **argv) {
cout << "main() is now executed" << endl;
return 0;
}
int b = foo("b"); /* global var init */
int foo(string s){
cout << "foo() is now executed for : " << s << endl;
return 42;
}
int c = foo("c"); /* global var init */
Result:
foo() is now executed for : a
foo() is now executed for : b
foo() is now executed for : c
main() is now executed
Answer:
No it is not fixed order.
See n3797, 3.6.2/5:
It is implementation-defined whether the dynamic initialization of a non-local variable with static or thread storage duration is done before the first statement of the initial function of the thread.