圆括号(10,20,30,40)之间的返回值列表? [英] return list of values between parenthesis (10, 20, 30, 40)?

查看:312
本文介绍了圆括号(10,20,30,40)之间的返回值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Visual Studio 2012 C ++ (不是C ++ / CLI)。

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);
}

我错误地生成了这个代码,错误时,我正在运行我的单元测试。我惊讶它的工作。当我运行它,它返回 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?

推荐答案

这是使用逗号运算符,它将从从左到右计算每个表达式,但只返回最后一个。如果我们查看 C ++标准草稿 部分 5.18 它说:

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:


<用逗号分隔的一对表达式从左到右求值; 83 与左表达式相关联的每个值计算和副作用在与右表达式相关联的每个值计算和副作用之前被排序。

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:


允许多个赋值语句,而不使用块语句,主要是在for循环的初始化和增量表达式中。

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

以前的线程使用C逗号运算符有一些真正的有趣

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.

启用警告,这总是一个好主意可能会帮助你在这里, gcc 使用 -Wall 我看到以下警告:

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);
              ^

,然后再两个。

这篇关于圆括号(10,20,30,40)之间的返回值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆