[英]Difference between cast used in Compound literals and that done on a pointer variable?
Consider the following code: 请考虑以下代码:
int main()
{
int *p;
++((int){5}); //compile without err/warning
&((int){5}); //compile without err/warning
++((char *)p); //Compile-time err: invalid lvalue in increment
&((char *)p); //Compile-time err: invalid lvalue in unary '&'
}
Why do the Compound Literals do not generate errors here? 为什么复合文字不会在这里产生错误?
It is because the "cast" in a compound literal is not a cast at all - it just looks like one. 这是因为复合文字中的“演员”根本不是演员 - 它只是一个。
A compound literal (which is the complete construction (int){5}
) creates an lvalue. 复合文字(完整构造
(int){5}
)创建左值。 However a cast operator creates only an rvalue, just like most other operators. 但是,与其他大多数运算符一样,强制转换运算符只会创建一个右值。
This example would be allowed (but useless, just like your int
examples): 这个例子是允许的(但是没用,就像你的
int
例子一样):
++((char *){(char *)p});
&((char *){(char *)p});
Compound literal doesn't have a cast in it. 复合文字中没有强制转换 。 The
(int)
part of your compound literals is not a cast. 复合文字的
(int)
部分不是强制转换。 It is just a type part of compound literal syntax. 它只是复合文字语法的一个类型部分。 So, the question in this case is whether a compound literal is an object, an lvalue.
因此,在这种情况下的问题是复合文字是一个对象,一个左值。 The answer is yes, a compound literal is an lvalue.
答案是肯定的,复合文字是左值。 For this reason you can apply any operators to it that require an lvalue (like
++
or &
). 因此,您可以将任何需要左值的运算符(如
++
或&
)应用于它。
The second part of your example contains casts. 示例的第二部分包含强制转换。 The result of a cast is always an rvalue.
演员表的结果总是一个右值。 You can't use
++
and &
with rvalues. 你不能使用
++
和&
rvalues。
The "cast" in a compound literal is actually not a cast , rather it is the type of the compound literal. 复合文字中的“强制转换”实际上不是 强制转换 ,而是复合文字的类型 。
So, (int){5}
is indeed more like an anonymous int
, hence a valid lvalue
which can be used anywhere an object of the same type ( int
in this case) could be used. 因此,
(int){5}
确实更像是一个匿名int
,因此可以使用一个有效的lvalue
,可以在任何可以使用相同类型的对象(在本例中为int
)的地方使用。
Whereas, (char *)p
is actually a cast ( rvalue
), so it cannot be incremented ++
or referenced &
. 然而,
(char *)p
实际上是一个强制转换 ( rvalue
),所以它不能递增++
或引用&
。
Read Dr.Doobs's in-depth article about compound literals. 阅读Dr.Doobs关于复合文字的深入文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.