gpt4 book ai didi

c - 两个结构体初始化的区别

转载 作者:行者123 更新时间:2023-12-04 08:18:25 25 4
gpt4 key购买 nike

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 namefollowed by a braceenclosed list of initializers is a compoundliteral. It provides an unnamed object whose value is given by theinitializer 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 automaticstorage duration shall be either an initializer list as describedbelow, or a single expression that has compatible structure or uniontype. In the latter case, the initial value of the object, includingunnamed members, is that of the expression.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com