使用自身地址初始化对象
Initializing an object with the address of itself
这是在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.
非静态结构的生命周期从进入声明它的块开始(称为自动存储持续时间):
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.
如果在与声明关联的块中指定初始化:
[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.
因此,在进入块时,该结构具有保证的存储空间和一个 常量地址,您可以在该结构的初始化中自由使用,因为初始化是保证发生的在结构的生命周期开始后。
对于静态结构,
Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
因此,一旦程序开始执行,该结构就会保证存储和常量地址,并且在该生命周期内但在标准执行协议(调用 main()
等)之前初始化其存储值。
来源:C99 draft。这些参考文献的 C11 文献是相同的。
Here 是一个演示。这在 -std=c99 -pedantic
和 -std=c11 -pedantic
.
下编译时没有警告
这是在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.
非静态结构的生命周期从进入声明它的块开始(称为自动存储持续时间):
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.
如果在与声明关联的块中指定初始化:
[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.
因此,在进入块时,该结构具有保证的存储空间和一个 常量地址,您可以在该结构的初始化中自由使用,因为初始化是保证发生的在结构的生命周期开始后。
对于静态结构,
Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
因此,一旦程序开始执行,该结构就会保证存储和常量地址,并且在该生命周期内但在标准执行协议(调用 main()
等)之前初始化其存储值。
来源:C99 draft。这些参考文献的 C11 文献是相同的。
Here 是一个演示。这在 -std=c99 -pedantic
和 -std=c11 -pedantic
.