Search code examples
c++initializationglobal-variablesunspecified-behavior

C++ initialization of namespace scope variable


Consider following program: (see live demo here.)

#include <iostream>
inline double fun()
{
    return 3.0;
}
extern double m;
double d2=m;
int main()
{
    std::cout<<d2;
}
double m=fun();

I was expecting to get output of program as 3.0 but it gives me output 0. Why?

It looks like variable d2 is initialized statically?

Shouldn't it be initialized dynamically?

I've tested it on g++ 4.8.1, 4.9.2 & MSVS 2010 & get 0 as an output.


Solution

  • Variables within a C++ file are initialized top-to-bottom. So m is initialized after d.

    There are some other subtleties.

    When the compiler can work it out, it sometimes emits data definitions for variables - setting a value to a known constant. These occur before the program is loaded.

    Then the order of initialization is the code segments - like constructors. These segments occur top to bottom in the compilation unit.

    In your case d=m I think copies the value from the slot for m. Which is set to 0.0

    Then m=fun() is called, copying the slot with the correct value.