两个结构初始化之间的区别

Difference between two struct initializations

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

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

并且:

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

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


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

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

也与 的两个答案有关。

在此声明中

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.