简体   繁体   中英

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.

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.

Yes, both d2 and m have static storage duration, because they are declared, undecorated, at namespace scope.

That means they are zero-initialised as a first step before any other initialisation happens. Then, d2 is set to m . It is not until after that, that m becomes 3.0 .

Consider the following, which is essentially the same thing:

int main()
{
   int x = 0, y = 0;
   y = x;
   x = 3;
}

Clearly, here, it is nonsense to expect y to be equal to 3 , but that's what you're doing.

If you expected the initialisation to happen like for function- static variables, where initialisation happens on first use ( sort of ), you were mistaken.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM