2

(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.

modeller
  • 3,770
  • 3
  • 25
  • 49
  • 1
    Within the same translation unit, yes. Otheriwse, no. – Damon Jul 11 '14 at 17:22
  • 1
    Check this link: [When are static and global variables initialized?][1] [1]: http://stackoverflow.com/questions/17783210/when-are-static-and-global-variables-initialized – VladimirM Jul 11 '14 at 17:22
  • 1
    Yes, the before main initialization of elements with static storage duration is guaranteed by the standard, but not the order of such initialization. Be careful with that, is known as the *static initialization fiasco* – Manu343726 Jul 11 '14 at 17:23

0 Answers0