c++ - 更改对象并在同一表达式中使用它但子表达式由逗号运算符分隔是否是未定义的行为?

标签 c++ comma-operator

您好,我在某个网站上找到了这个程序。让我感到困惑的是,这个程序修改了同一个对象并在同一个表达式中使用它,因此它是未定义的行为吗?还是可以,因为逗号运算符 , 保证从左到右求值?

int x = 10, y;

// The following is equavalent to y = x++ 
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);

// Note that last expression is evaluated 
// but side effect is not updated to y 
printf("y = %d\n", y);
printf("x = %d\n", x);

输出:

x = 11
x = 12
y = 12
x = 13

最佳答案

Comma operator , Guarantees evaluation from left-to-right?

是的,有一个警告。来自 https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator

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).

警告不适用于您的情况,因为您没有使用任何用户定义的逗号运算符函数。


除非您从事对编译器进行压力测试的工作,否则您永远不应该编写那样的代码。使用更简单、更容易理解的代码。

x++;
printf("x = %d\n", x);

++x;
printf("x = %d\n", x);

x++;
y = x;

关于c++ - 更改对象并在同一表达式中使用它但子表达式由逗号运算符分隔是否是未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953159/

相关文章:

c++ - 不寻常的编译器错误转换为无效?

c++ - 使用 C++ 尾随返回类型时 auto 是什么意思?

c++ - 3D/FPS 相机问题 - SDL2

三元语句中的 C 逗号

c++ - 滥用逗号运算符来柯里化(Currying)函数参数

c - 逗号运算符和分号之间有什么实际的语义区别吗?

c++ - C++14 中的简单 constexpr LookUpTable

c++: #include 和不同的文件类型

c++ - 如何在不关闭VTK渲染窗口的情况下使代码流畅?

javascript - return void 0 === i && (i = 3), 0 === i 是什么意思? ( ..A.. ) : ( . .B.. ) 呢?