This code compiles fine:
extern int i = 10;
void test()
{
std::cout << \"Hi\" << i << std::endl;
}
While this code g
By adding an initialiser to the declaration, it becomes a definition of the global variable. It's equivalent to the same definition without extern
, which is what your book means when it says it "overrides the extern".
While global variables can be declared (using extern
) inside a function, they cannot be defined there, only at namespace scope. That's why the second snippet is an error.
If you want to know why the designers of C (whence these rules came to C++) chose to allow declarations but not definitions here, then I'm afraid I don't know the language's history in enough detail to answer.