Following is a very simple c++ code:-
#include <iostream>
using namespace std;
int i;
i = 2; //error at line 5
int main()
{
cout << i << endl;
return 0;
}
Total 3 errors are produced due to line 5:-
this declaration has no storage class or type specifier
missing type specifier - int assumed. Note: C++ does not support default-int
'int i': redefinition
I knew that line 5 is syntactically wrong but I couldn't find any reason for it.
I have just started learning C++ from the book C++: A Complete Reference by Herbert Schildt. In chapter 2 while understanding extern keyword, it was wriiten that
A declaration declares the name and type of an object. A definition causes storage to be allocated for the object.
From this, I deduced that statements of the form {type}{variable_name} are declarations while first assignment statements i.e., {variable_name} ={first_value} can be thought of as definition.
But for global variables, declarations are definitions because if they aren't initialized, they are given a default value. So in the given code, at line 4, i should be initialized with default value 0 and then, at line 5, i is just given another value, 2 but outside main().
Usually, global variables are initialized inside main and they cannot be assigned values like this outside main. If the same is done with any other type of variable like with local variables, no error is raised.
Similar question was asked in this thread.
I couldn't understand the answer given by paxdiablo completely. It says before main() is being compiled, there is no b and gave 2 solutions. Either initailize variable b while declaring it before main() gets invoked or use extern to tell the compiler that the variable, b is used somewhere else.
I used the former solution in a slightly different way. First, I declared the global variable, i and then I assigned it a value before main() gets invoked.
So, why globals (whether static or not) can't be defined or assigned to a value in a separate line of code outside main() even if the assignment is done before main()?
Note: I have just started studying C++. So it may be possible that my deductions are wrong. Before C++, I did python, so it's becoming a bit difficult for me to understand the initialisation and compilation order of the C++ code. So, sorry if it becomes a little too inconvenient for you all.