括号表达式的赋值
Assignment of a parenthesized expression
考虑以下片段:
int a, b, c;
a = (b = 3, c = 4, 5, 6);
事实证明,执行完这些行后,b 的值为 3,c 的值为 4。到目前为止没有意外。但是 a 的值为 6。这是为什么?
还有,这个有什么用吗?
因为 ,
运算符丢弃了左边的所有操作数,并且由于 6
是最右边的操作数,所以它是唯一没有被丢弃的操作数。
这来自 § 6.5.17 n1570 草案
The left operand of a comma operator is evaluated as a void expression; there is a
sequence point between its evaluation and that of the right operand. Then the right
operand is evaluated; the result has its type and value.
EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot
appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists
of initializers). On the other hand, it can be used within a parenthesized expression or within the second
expression of a conditional operator in such contexts. In the function call
f(a, (t=3, t+2), c)
the function has three arguments, the second of which has the value 5.
你可以阅读更多here
每当您在赋值语句中使用分隔符(即“,”)时,它都会分配最后一个值。例如
诠释我=(2,3);
// 我 = 3;
变量我得到的值是 3 而不是 2.
考虑以下片段:
int a, b, c;
a = (b = 3, c = 4, 5, 6);
事实证明,执行完这些行后,b 的值为 3,c 的值为 4。到目前为止没有意外。但是 a 的值为 6。这是为什么?
还有,这个有什么用吗?
因为 ,
运算符丢弃了左边的所有操作数,并且由于 6
是最右边的操作数,所以它是唯一没有被丢弃的操作数。
这来自 § 6.5.17 n1570 草案
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers). On the other hand, it can be used within a parenthesized expression or within the second expression of a conditional operator in such contexts. In the function call
f(a, (t=3, t+2), c)
the function has three arguments, the second of which has the value 5.
你可以阅读更多here
每当您在赋值语句中使用分隔符(即“,”)时,它都会分配最后一个值。例如
诠释我=(2,3);
// 我 = 3;
变量我得到的值是 3 而不是 2.