Resolve the problem that C++ global variables can only be initialized and not assigned
- 2020-06-07 05:03:15
- OfStack
In C++, global variables can only be declared and initialized, not assigned
In other words, the following is not allowed:
#include <cstdio>
using namespace std;
int a;
a = 2;
int main() {
return 0;
}
Error message:
C++ requires a type specifier for all declarations
The difference between declaration, initialization, and assignment:
Declaration: int a;
Initialization: int a = 2; (An assignment at the time of declaration is called initialization)
Assignment: a = 2;
Definition only (int a;) Before allocating storage space, initialization must have storage space to initialize
It is possible to declare a global variable with an assignment (i.e., initialization), but if you declare it first, do not assign it, and then assign it later, the program will not execute here and will not compile.