return list of values between parenthesis (10, 20, 30, 40)?

丶灬走出姿态 提交于 2019-11-26 21:42:03

问题


I am working in C++ (not C++/CLI) in Visual Studio 2012.

I don't understand why this code works, I would have expected it to fail at compilation time, but it doesn't even fail at runtime:

double MyClass::MyMethod() const
{
    //some code here        
    return (10, 20, 30, 40);
}

I produced this code by mistake, wasn't on purpose, I noticed the mistake when I was running my Unit Tests. And I am surprised it works. When I run it, it returns 40, the last number on the list.

Can someone explain me what this syntax means and why it works?


回答1:


This is using the comma operator which will evaluate each expression from left to right but only return the last. If we look at the draft C++ standard section 5.18 Comma operator it says:

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded value expression (Clause 5).83 Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.

the linked article gives the most common use as:

allow multiple assignment statements without using a block statement, primarily in the initialization and the increment expressions of a for loop.

and this previous thread Uses of C comma operator has some really interesting examples of how people use the comma operator if you are really curious.

Enabling warning which is always a good idea may have helped you out here, in gcc using -Wall I see the following warning:

warning: left operand of comma operator has no effect [-Wunused-value]
  return (10, 20, 30, 40);
              ^

and then two more of those.




回答2:


The comma operator is a 'sequence point' in C++, often used to initialise multiple variables in for loops.

So the code is evaluating a series of integers, one at a time, as single expressions. The last of these is the returned value, and the return statement as a whole is equivalent to simply return (40);




回答3:


the expression (10, 20, 30, 40) is actually a series of 4 expressions separated by , You can use , to separate multiple expressions and the result is the evaluation of the last one.




回答4:


You have used the , i.e. comma operator

return () is valid.

and so is return (/*valid evaluation*/)

Comma operator returns the last value i.e 40



来源:https://stackoverflow.com/questions/20001349/return-list-of-values-between-parenthesis-10-20-30-40

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!