c++ - 在 C++ 中使用逗号运算符时的未定义行为

标签 c++ c++11 c++17 undefined-behavior expression-evaluation

我正在尝试学习如何在 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;
产生未定义的行为。
我的问题是:
  • 但是在逗号运算符中使用的相同语句是否会产生 UB(如上面的代码所示)?也就是说,下面给出的语句是否会产生 UB。
  • 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-defined operator, 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/

    相关文章:

    c++ - 类型特征 : Check if class have specific function (maybe inherit)

    c++ - 公共(public) : static constant string declaraion/initialization issue

    c++ - C++ 1z中的编译时反射?

    c++ - 整数在 Excel 2010 与 Excel 2003 中的表示(C++ 插件)

    c++ - 如何将轴移动到 QCustomPlot 的中间

    java - 如何将 jstring 转换为 wchar_t *

    c++ - 可变参数模板重载解析

    c++ - 使用模板变量类型执行上下文特定操作

    c++ - constexpr if 和 static_assert

    c++ - 在 C 中使用 C++ API?