Why does initializing an extern variable inside a function give an error?

前端 未结 5 1447
温柔的废话
温柔的废话 2020-12-05 10:10

This code compiles fine:

extern int i = 10;

void test()
{
    std::cout << \"Hi\" << i << std::endl;
}

While this code g

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 10:23

    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.

提交回复
热议问题