gpt4 book ai didi

标量类型的复合文字

转载 作者:行者123 更新时间:2023-12-01 13:52:01 24 4
gpt4 key购买 nike

c99复合文字可用于例如初始化指针:

int *p = (int []) {1, 2, 3, 4};

而这通常用于 struct s 它也可用于初始化匿名数组(参见示例)。但是,如果我理解这正确初始化标量指针是这样的:
int *p = &(int) {4};

也是有效的。让我感到困惑的是 gcc 上的声明站点,“也允许标量类型和 union 类型的复合文字,但复合文字等同于强制转换。”它们是否只是意味着使用地址运算符 &在匿名标量前面是一种类型转换形式吗?

最佳答案

根据定义,复合文字不包含 &地址运营商。从 N1570 6.5.2.5/p3复合字面量:

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal.



现在,他们的声明:

Compound literals for scalar types and union types are also allowed, but then the compound literal is equivalent to a cast.



如果我读对了,那就错了。复合文字和强制转换运算符之间的根本区别在于,前者是左值,如 N1570 6.5.2.5/p4 (强调我的):

Otherwise (when the type name specifies an object type), the type of the compound literal is that specified by the type name. In either case, the result is an lvalue.



而后者不是, 6.5.4/p5类型转换运算符(强调我的):

Preceding an expression by a parenthesized type name converts the value of the expression to the named type. This construction is called a cast.104)

104) A cast does not yield an lvalue. Thus, a cast to a qualified type has the same effect as a cast to theunqualified version of the type.

关于标量类型的复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021874/

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