gpt4 book ai didi

c - 使用自身地址初始化对象

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

这是在C99和C11中定义的吗?

struct A
{
struct A* first;
int value;
};

{ // inside a function
struct A a = { &a };
a.first->value = 123;
}

并使用说明符静态:

{    // inside a function
static struct A a = { &a };
a.first->value = 123;
}

最佳答案

这是明确定义的行为。

根据 C 标准 §6.2.4(强调我的):

An object exists, has a constant address, and retains its last-stored value throughout its lifetime.

非静态结构的生命周期从进入声明它的 block 开始(称为自动存储持续时间):

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

如果在与声明关联的 block 中指定初始化:

[the initialization] is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

因此在进入 block 时,该结构已保证存储空间和一个常量地址,您可以在该结构的初始化中自由使用它,因为初始化保证在该结构的生命周期之后发生结构已经开始。

对于静态结构,

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

因此,一旦程序开始执行,该结构就保证了存储空间和常量地址,并且它的存储值在该生命周期内但在标准执行协议(protocol)(调用 main() 等)之前被初始化).

来源:C99 draft .这些引用文献的 C11 文献是相同的。

Here是一个演示。这在 -std=c99 -pedantic-std=c11 -pedantic 下编译时没有警告。

关于c - 使用自身地址初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32023405/

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