在 C++
中,可以执行以下操作:
int f(int& a, int& b, int& c, int& d) {
return (a, b, c, d); // here
}
首先,这个只返回最后一项的“括号”表达式在语言中的名称(以及 cppreference 上的链接)是什么;
其次,假设代码变为:
int f(int& a, int& b, int& c, int& d) {
return (a += 2, d += 5, b -= 3, c = a + b + d, d); // here
}
这些“括号”表达式的求值顺序是固定的吗?如果是这样,我是否可以保证 f
会更改 a
、b
、c
和 的值>d
从左到右,并返回 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;
我的意思是:逗号运算符计算但丢弃左侧的元素并返回右侧的元素(如果左侧的元素不是重新定义了逗号运算符的对象)。
而且不需要括号;你也可以写。
return a, b, c, d;
Second, let's say the code becomes [...] Is the order of evaluation of theses "parenthesis" expressions fixed?
是的;从左到右。
寻找“序列点”以获取更多信息。
从
return a += 2, d += 5, b -= 3, c = a + b + d, d;
你得到的结果和你从中得到的结果完全一样
a += 2; d += 5; b -= 3; c = a + b + d; return d;
还考虑到 a
、d
、b
和 c
是 int
并且 int
不是重新定义逗号运算符的类。
但不要将“逗号运算符”中的逗号与函数调用中分隔参数的逗号混淆。第一个是“序列点”,第二个不是。
我的意思是:与
int i = 0;
return i++, i++, i++;
返回值已定义(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?
是的。
并且(恕我直言)这是一个非常有用的功能。
关于c++ - C++ 中括号和逗号表达式中类型的计算顺序 (x0 = y0, x1 = y1, x2 = x0, ...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48915998/