global variable initialization

2020-08-01 06:37发布

问题:

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 b;
int main(int argc, char *argv[]) 
{
  cout<<a<<endl;
  cout<<b<<endl;
  return 0;
}
b=100;

There is an error while I run this.Isn't it true that 'b' assigned to 100 before main() is called?And the error is C++ requires a type specifier for all declarations

回答1:

The problem here is not initialisation order: b is indeed initialised before main starts running.

The problem is the "visibility" of b. At the point where main is being compiled, there is no b.

You can fix it by either moving the definition/initialisation of b to before main:

#include <iostream>

using namespace std;
int a = 99;
int b = 100;
int main (int argc, char *argv[]) {
    cout << a << '\n';
    cout << b << '\n';
    return 0;
}

or simply indicate that b exists:

#include <iostream>

using namespace std;
int a = 99;
extern int b;
int main (int argc, char *argv[]) {
    cout << a << '\n';
    cout << b << '\n';
    return 0;
}
int b = 100;

Neither of those two solutions change when b is created or initialised at run-time, they simply make b available within main.



回答2:

The problem is here: cout<<b<<endl;

You can't access the variable before it's declaration.



回答3:

Your lecturer is wrong; global variables are initialised in order of definition, not declaration.

For example,

#include <iostream>
struct S { S(const char *s) { std::cout << s << '\n'; } };
extern S a;    // declaration
extern S b;    // declaration
int main() { }
S b("b");      // definition
S a("a");      // definition

will print

b
a

The code you posted doesn't work because b is not even declared at the point of use. A declaration (for example, extern int b), is required because C++ (like C) was originally designed as a one-pass compiler.



回答4:

Read carefully.

A variable defined outside any function (B) is initialized before main is invoked (not compiled).

To be compiled correctly B should be defined(and declared) before it's first use (and that's your error: B is used before been declared anywhere).



标签: c++