gpt4 book ai didi

c - C 中的声明或定义

转载 作者:太空狗 更新时间:2023-10-29 16:25:13 26 4
gpt4 key购买 nike

来自 External Variables Wiki :

If neither the extern keyword nor an initialization value are present, the statement can be either a declaration or a definition. It is up to the compiler to analyse the modules of the program and decide.

我没能完全理解这个关于 C 的陈述的含义。例如,它是否意味着:

int i;

不一定是声明(正如我到现在为止一直假设的那样),但也可以是定义(根据同一网页上的定义和声明的定义,没有双关语意)?

简而言之,就是上面的语句:一种。只是一个声明,或者b.声明+定义?

引用:Variable declaration and definition

收到的答复摘要:

                         Declaration    Definition    Tentative Definition   Initialized 
int i; (inside a block) Yes Yes No No
int i=5; (inside a block) Yes Yes No Yes(to 5)
int i; (otherwise) Yes No Yes Yes(to 0)
extern int i; Yes No No No


All definitions are declarations but not vice-versa.

最佳答案

假设它在文件范围内,它是一个“暂定定义”。来自 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.

这意味着在翻译单元中也包含以下内容也是有效的:

int i = 42;

由于该声明具有显式初始化程序,因此它是变量 i 的定义。

就好像声明在 block 范围内一样,标准说明如下(6.2.2/2“标识符的链接”):

Each declaration of an identifier with no linkage denotes a unique entity.

...

(paragraph 6) The following identifiers have no linkage: ... a block scope identifier for an object declared without the storage-class specifier extern.

所以在 block 范围内,声明也是一个定义。

关于c - C 中的声明或定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4769599/

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