gpt4 book ai didi

我们可以在结构定义之前在文件范围内声明结构对象吗?

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

根据下面给出的代码及其答案:

Question: Which of the following structure declarations will throw an error?

  1. struct temp { char c; } s;
    int main(void) {}
  2. struct temp { char c; };
    struct temp s;
    int main(void) {}
  3. struct temp s; 
    struct temp { char c; };
    int main(void) {}
  4. None of the above.

Answer: 4

这是正确的吗?我们可以先声明一个结构对象,然后再声明结构定义吗?

最佳答案

是的,C 有时候很奇怪。因为该变量在文件范围内并且没有初始化器或存储类说明符,所以它构成了一个暂定定义。 C标准定义如下:

6.9.2 External object definitions

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.

我强调了相关部分。因为你的变量没有初始化器,就好像你把它写在文件的最后并初始化为零。文件的物理布局并不重要,因为从逻辑上讲,结构类型的定义在文件末尾可用。

所以答案确实是(4)。我不会在现实生活中编写这样的代码,但是,这在 C 生态系统中非常困惑,几乎所有东西都必须预先声明才能使用。

关于我们可以在结构定义之前在文件范围内声明结构对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55780564/

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