gpt4 book ai didi

c - 将打印哪个值?

转载 作者:行者123 更新时间:2023-12-05 01:29:59 25 4
gpt4 key购买 nike

void main()
{
extern int i;
printf("%d\n",i);
}
int i;//definetion
int i=35;//definition

上面代码中int i表示i=0;int i=35表示i=35.

那么,如果编译器没有给出 redefinition 错误,那么将打印哪个值?

最佳答案

在 ansi 标准中,他们称 int x; 为“暂定”定义。

这是 ansi 标准所说的:

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.

举例说明:

     int i1 = 1;          /*  definition, external linkage */
static int i2 = 2; /* definition, internal linkage */
extern int i3 = 3; /* definition, external linkage */
int i4; /* tentative definition, external linkage */
static int i5; /* tentative definition, internal linkage */
int i1; /* valid tentative definition, refers to previous */
int i2; /* $3.1.2.2 renders undefined, linkage disagreement */
int i3; /* valid tentative definition, refers to previous */
int i4; /* valid tentative definition, refers to previous */
int i5; /* $3.1.2.2 renders undefined, linkage disagreement */



extern int i1; /* refers to previous, whose linkage is external */
extern int i2; /* refers to previous, whose linkage is internal */
extern int i3; /* refers to previous, whose linkage is external */
extern int i4; /* refers to previous, whose linkage is external */
extern int i5; /* refers to previous, whose linkage is internal */

根据我的理解,您可以根据需要对同一对象拥有任意多个暂定定义,但最多只有一个定义(带有初始值设定项)。如果没有定义,则将暂定定义转换为文件末尾带有 initializer == 0 的定义。

换句话说,打印的值是35,因为有初始化器。

关于c - 将打印哪个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21184901/

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