我正在尝试学习如何在 C++ 中评估表达式。所以尝试和阅读不同的例子。以下是我无法理解它是否会产生未定义行为的代码。代码来自 here .所以我想既然他们已经使用过它,这一定不是 UB。但我有我的怀疑。
#include <iostream>
int main()
{
int n = 1;
//std::cout << n << " " << ++n << std::endl;//this is undefined behavior i am sure
int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);//will this also produce UB because here also we have cout in the same manner as above?
std::cout << "m = " << (++m, m) << '\n';
}
正如您在上面的代码中看到的那样,我确信该语句:cout << n << " " << ++n << endl;
产生未定义的行为。我的问题是:
int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);
PS:我知道从 C++11 开始我们使用序列之前等而不是序列点,所以我为什么要根据当前标准进行解释。
最佳答案
来自 cppreference 的同一页面:
In a comma expression
E1, E2
, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-definedoperator,
cannot guarantee sequencing) (until C++17).
由于代码中的逗号运算符是内置的,因此
++n
之间的顺序, std::cout << "n = " << n << '\n'
其他表达式定义明确。没有未定义的行为。因为您可能已经阅读了以上内容,这里是 wording from the standard :
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression. The left expression is sequenced before the right expression ([intro.execution]).
关于c++ - 在 C++ 中使用逗号运算符时的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69313026/