标量类型的复合文字

Compound literals for scalar types

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

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

虽然这通常用于 structs,但它也可用于初始化匿名数组(参见示例)。但是如果我理解正确初始化标量指针是这样的:

int *p = &(int) {4};

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

根据定义,复合文字不包含 & address-of 运算符。来自 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.

如果我没看错的话,那就错了。复合文字和 cast 运算符之间的根本区别在于前者是 lvalue,如 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.