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

前端 未结 5 1466
温柔的废话
温柔的废话 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:46

    The simplest way to put it:

    The purpose of the extern keyword is to declare an object without defining it. By defining it, you're basically telling the compiler "Do not assign a value but assign a value". That doesn't make sense - It should never be done, inside or outside a function. Most compilers will either warn you and proceed anyway, or they won't compiler at all and give an error.

    Though it's beyond the scope of this question to explain in detail what extern does, you may find it useful to read the answers for this question.

提交回复
热议问题