gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:35:02 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com