C++ 中括号和逗号表达式中类型的计算顺序 (x0 = y0, x1 = y1, x2 = x0, ...)

Evaluation order in parenthesis and comma expression in C++ of the type (x0 = y0, x1 = y1, x2 = x0, ...)

C++ 中,可以执行以下操作:

int f(int& a, int& b, int& c, int& d) { 
    return (a, b, c, d); // here
}

首先,这个 "parenthesis" 表达式在语言中的名称是什么(在 cppreference 上 link),其中只有最后一个词是 returned;

其次,假设代码变为:

int f(int& a, int& b, int& c, int& d) { 
    return (a += 2, d += 5, b -= 3, c = a + b + d, d); // here
}

这些"parenthesis"表达式的求值顺序是固定的吗?如果是这样,我是否可以保证 f 将从左到右更改 abcd 的值,并且 return d 的正确更新值,就好像它是:

int f(int& a, int& b, int& c, int& d) { 
    a += 2;
    d += 5;
    b -= 3;
    c = a + b + d;
    return d;
}

最后,纯粹在C++11中(因为C++14中不再存在这个问题,因为constexpr没有那么强的要求),这个括号表达式可以吗在单个 constexpr 函数中编写多个计算?

First, what is the name in the language (and link on cppreference) to this "parenthesis" expression where only the last term is returned;

"comma operator".

我的意思是:逗号运算符计算但丢弃左边的元素和 return 右边的元素(如果左边的元素不是重新定义了逗号运算符的对象)。

并且不需要括号;你也可以写。

return a, b, c, d;

Second, let's say the code becomes [...] Is the order of evaluation of theses "parenthesis" expressions fixed?

是;从左到右。

寻找 "sequence point" 了解更多信息。

return a += 2, d += 5, b -= 3, c = a + b + d, d;

你得到的结果与你从

得到的结果完全一样
a += 2; d += 5; b -= 3; c = a + b + d; return d;

还考虑到 adbcintint 不是重新定义逗号运算符的 class。

但不要将 "comma operator" 中的逗号与函数调用中分隔参数的逗号混淆。第一个是 "sequence point",第二个不是。

我的意思是:与

int i = 0;

return  i++, i++, i++;

returned 值已定义 (2);如果 foo() 是一个接收三个整数的函数,并且

int i = 0;

foo(i++, i++, i++);

你知道 foo() 接收一个零、一个和一个二,但顺序未指定(第一个参数可以是 0,第三个或第二个参数可以是 2相反)。

Finally, purely in C++11 [...] can this parentheses expressions be used to write several computation in a single constexpr function?

是的。

并且(恕我直言)这是一个非常有用的功能。