以下两个 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
};
也与 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/