简体   繁体   English

使用自身的地址初始化对象

[英]Initializing an object with the address of itself

Is this defined in C99 and C11? 这是在C99和C11中定义的吗?

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

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

And using specifier static: 并使用说明符静态:

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

This is well-defined behavior. 这是明确定义的行为。

According to the C Standard §6.2.4 (emphasis mine): 根据C标准§6.2.4(强调我的):

An object exists, has a constant address, and retains its last-stored value throughout its lifetime. 存在一个对象, 具有一个常量地址,并在其整个生命周期内保留其最后存储的值。

The lifetime of the non-static struct begins with the entry into the block in which it is declared (known as automatic storage duration ): 非静态结构的生命周期从进入声明它的块开始(称为自动存储持续时间 ):

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. 对于没有可变长度数组类型的此类对象,其生命周期从entry进入与其关联的块,直到该块的执行以任何方式结束。

And if, in the block with which the declaration is associated, you specify an initialization: 如果在与声明关联的块中指定了初始化:

[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. 否则,每次达到声明时,该值将变为不确定。

So upon entering the block, the struct has guaranteed storage and a constant address that you are free to use in an initialization for that struct, since the initialization is guaranteed to happen after the lifetime of the struct has started. 因此,在进入块时,struct保证了存储和一个常量地址 ,您可以在该结构的初始化中自由使用,因为初始化保证在结构的生命周期开始之后发生。

For the static struct, 对于静态结构,

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup. 它的生命周期是程序的整个执行,它的存储值只在程序启动之前初始化一次。

So the struct has guaranteed storage and a constant address as soon as program execution starts, and its stored value is initialized during that lifetime but prior to the standard execution protocol (calling main() , etc). 因此,只要程序执行开始,结构就保证了存储和常量地址,并且它的存储值在该生命周期内但在标准执行协议(调用main()等之前)初始化。

Source: C99 draft . 资料来源: C99草案 The C11 literature for these references is identical. 这些参考文献的C11文献是相同的。

Here 'sa demo. 是一个演示。 This compiles without warnings under -std=c99 -pedantic and -std=c11 -pedantic . 这在-std=c99 -pedantic-std=c11 -pedantic下编译时没有警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM