简体   繁体   English

分配中使用逗号运算符

[英]Comma operator used in assignment

Consider the code: 考虑代码:

int i, j;
i = (i = 1, j = 3);
i++;
cout<<i<<" "<<j;

This printed 4 3 (c++14). 这打印了4 3 (c ++ 14)。

I read that the comma operator evaluates the expression on its left and returns the one on its right. 我读到逗号运算符在其左侧计算表达式,并在其右侧返回表达式。 Now if that is correct, I want to know what is the return value of j = 3? 现在,如果这是正确的,我想知道j = 3的返回值是多少? Is it the rvalue? 是右值吗? Or a reference to the lvalue? 还是对左值的引用?

How does this actually work? 这实际上如何工作?

To calculate (i=1, j=3), it calculates, from left to right, the expressions separated by comma, and returns the value of the last (rightmost) expression. 为了计算(i = 1,j = 3),它从左到右计算用逗号分隔的表达式,并返回最后一个(最右边)表达式的值。 So it calculates i=1 (i becomes 1), then it calculates j=3 (j becomes 3), then returns 3. 因此,它计算i = 1(i变为1),然后计算j = 3(j变为3),然后返回3。

After calculating (i=1, j=3), which returned 3, it performs the assignment, which sets i to 3. 计算(i = 1,j = 3)后返回3,然后执行赋值,将i设置为3。

Then i++ is calculated, which sets i to 4. 然后计算i ++,将i设置为4。

Then i and j are printed. 然后,i和j被打印。

I want to know what is the return value of j = 3? 我想知道j = 3的返回值是多少?

Assignment operations* return (or "evaluate to") a reference to the left-hand side of the operation, in this case j . 赋值运算*返回(或“评估为”)对该运算左侧的引用(在本例中为j

So i = (i = 1, j = 3); 所以i = (i = 1, j = 3); is identical to: 等同于:

i = 1;
j = 3;
i = j;

*For built-in types that is. *对于内置类型。 Custom operator= overloads may return whatever they want, although it's recommended to return a reference to *this as it is the expected behavior among C++ programmers. 自定义operator=重载可能会返回所需的任何内容,尽管建议返回对*this的引用,因为这是C ++程序员的预期行为。

The assignment operator returns an lvalue referring to the left operand. 赋值运算符返回一个引用左操作数的左值。 It groups right-to-left. 它从右到左分组。 ( [expr.ass] ). [expr.ass] )。 Note that saying returning a reference to the lvalue doesn't make sense - it either returns an lvalue or not. 请注意,说返回对左值的引用没有意义-它要么返回左值,要么不返回左值。

The comma operator performs the value computations and side effects from the left operand, discards them, and then does the same for the right operand. 逗号运算符从左操作数执行值计算和副作用,将其丢弃,然后对右操作数执行相同的操作。 ( [expr.comma] ) [expr.comma]

So refactoring the comma operator would produce the following equivalent code: 因此,重构逗号运算符将产生以下等效代码:

i = 1;      // left operand, value discarded
i = j = 3;  // right operand, value preserved
i++;

and then refactoring the compound assignment would produce the following still equivalent code: 然后重构复合分配将产生以下仍等效的代码:

i = 1;
j = 3;     // rightmost assignment
i = j;     // leftmost assignment
i++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM