gpt4 book ai didi

c - 当变量已经声明为全局变量时,使用 extern 关键字初始化变量时,存储在变量中的值是多少?

转载 作者:行者123 更新时间:2023-11-30 14:59:50 25 4
gpt4 key购买 nike

当我们声明一个全局变量时,它会被初始化为其默认值。但是,当我们使用 extern 关键字初始化变量时,为什么变量会保留使用 extern 关键字初始化时的值呢?

例如,在下面的代码中,为什么输出是 9 而不是编译时错误?由于变量 x 没有来自任何其他源文件的外部链接,因此 x 有两个副本,并且我们正在初始化该变量两次,因此这应该是一个错误。请澄清这一点;我对这段代码的流程有点困惑。

#include <stdio.h>

extern int x=9;
int x;

int main()
{
printf("%d",x);
return 0;
}

最佳答案

extern int x = 9;int x = 9; 含义相同。 extern 关键字对于已经具有外部链接和初始值设定项的定义无效。

int x; 被称为暂定定义

C11 6.9.2/2 对此进行了很好的描述:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

此翻译单元确实包含x的外部定义,因此暂定定义无效。外部定义在暂定定义之前还是之后并不重要。

“外部定义”意味着文件范围内的非暂定定义 - 不要与 extern 或“外部链接”混淆,尽管在您的示例中 x 确实如此碰巧有外部链接。

所以你的代码与:

int x = 9;

关于c - 当变量已经声明为全局变量时,使用 extern 关键字初始化变量时,存储在变量中的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com