c - 两个结构体初始化之间的差异

标签 c struct initialization compound-literals

以下两个 Struct 初始化有什么区别?

Car ford = {
    .name = "Ford F-150",
    .price = 25000
};

还有:

Car dodge = (Car) {
    .name = "Ram",
    .price = 1000
};

来自Compiler Explorer ,看起来两者生成相同的代码:

enter image description here


(StructName) 在结构前面有什么作用?在进行复杂的初始化时似乎有必要,例如:

CarPtr mazda = & (Car) {
    .name = "Mazda",
    .price = 20000
};

也与 Possible to initialize/assign a struct pointer? 的两个答案相关.

最佳答案

在此声明中

Car dodge = (Car) {
    .name = "Ram",
    .price = 1000
};

创建了两个 Car 类型的对象。第一个是未命名的复合文字

(Car) {
    .name = "Ram",
    .price = 1000
}

用于初始化另一个命名对象闪避。

来自 C 标准(6.5.2.5 复合文字)

3 A postfix expression that consists of a parenthesized type name followed by a braceenclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

实际上类似于下面的声明

Car ford = {
    .name = "Ford F-150",
    .price = 25000
};

Car dodge = ford;

不同之处在于,在上一个示例中,我们创建了一个更多的命名对象。

来自 C 标准(6.7.9 初始化)

13 The initializer for a structure or union object that has automatic storage duration shall be either an initializer list as described below, or a single expression that has compatible structure or union type. In the latter case, the initial value of the object, including unnamed members, is that of the expression.

关于c - 两个结构体初始化之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604080/

相关文章:

c - 理解 typedef 和 struct

C中的结构是否总是以分号结尾

c - C中结构的不同语法

C:动态分配时通过引用传递

c++ - 通过代码构造std::array并初始化元素对象

C 结构未初始化的外部构造函数

c - 如何正确使用 fscanf 和 fgets 读取文件

c - 创建链表时不需要创建实际节点吗?

c++ - 结构对齐填充、填充的最大尺寸和结构成员的顺序

c - 未初始化的字符默认为@