源码

首页 » 归档 » 源码 » c – 为什么在函数内初始化extern变量会产…

c – 为什么在函数内初始化extern变量会产…


这段代码很好编译:

extern int i = 10;

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

虽然此代码给出了错误:

void test()
{
    extern int i = 10;
    std::cout << "Hi" << i << std::endl;
}

error: ‘i’ has both ‘extern’ and initializer

我在C++ Primer读到这个:

Any declaration that includes an explicit initializer is a definition.
We can provide an initializer on a variable defined as extern, but
doing so overrides the extern. An extern that has an initializer is a
definition. It is an error to provide an initializer on an extern inside a
function
.

有人可以提供一个解释,说明为什么这是一个错误,如果在函数本地完成,而在全局范围允许相同?

(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/c-weishenmezaihanshuneichushihuaexternbianlianghuichan.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9月 27, 2019 at 02:15 上午

热评文章