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

标签 c++ c++11 constexpr operator-precedence comma-operator

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 会更改 abc 的值>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;

"comma operator" .

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

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

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;

还考虑到 adbcint 并且 int 不是重新定义逗号运算符的类。

但不要将“逗号运算符”中的逗号与函数调用中分隔参数的逗号混淆。第一个是“序列点”,第二个不是。

我的意思是:与

int i = 0;

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

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

int i = 0;

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

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

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/

相关文章:

c++ - 派生类是否为成员变量分配内存?

c++ - 在构造函数的初始化列表中使用 std::initializer_list 初始化 std::array

c++ - 类里面不能有自己类型的常量?

c++ - reinterpret_cast 用法之间的区别

c++ - VS 2012 : Debugger: "Break all in 5 seconds"

c++ - 使用 std::remove_reference 获取 STL 容器的元素迭代器

c++ - 为什么不完整类型的智能指针数据成员和原始指针数据成员在其父级析构时具有不同的行为?

c++ - std::move on std::string 是否保证 .c_str() 返回相同的结果?

c++ - ADL 在 constexpr 函数中不起作用(仅限 clang)

c++ - 如何编写 constexpr 交换函数来更改整数的字节顺序?