In principle, a variable defined outside any function (that is, global, namespace, and class static variables) is initialized before main() is invoked. Such nonlocal variables in a translation unit are initialized in their declaration order
Above are the lines from the class notes given by my lecturer.
#include <iostream>
using namespace std;
int a=99;
int main(int argc, char *argv[])
{
cout<<a<<endl;
cout<<b<<endl;
return 0;
}
int b=100;
There is an error while I run this. Isn’t it true that b assigned to 100 before main() is called?
The problem here is not initialisation order:
bis indeed initialised beforemainstarts running.The problem is the “visibility” of
b. At the point wheremainis being compiled, there is nob.You can fix it by either moving the definition/initialisation of
bto beforemain:or simply indicate that
bexists:Neither of those two solutions change when
bis created or initialised at run-time, they simply makebavailable withinmain.