gpt4 book ai didi

c - C中的关系运算符有固定的求值顺序吗?

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

问题是这样的:

With int a,b,c;, is a = a * b + a; equivalent to (c = a * b)!=(a = c + a); with respect to modification of a?

乍一看,我认为它们是相同的,但是规范是否说在 expr1 != expr2 中,expr1 将始终在 expr2?我认为事实并非如此,但我找不到这方面的明确来源。

此外,我对 http://en.cppreference.com/w/c/language/eval_order 中的发现感到困惑:

The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments.

(since C11)

这是否意味着我可以将其解释为自 C11 以来,上述语句将具有固定的求值顺序(因为涉及赋值),但不能解释为 C11 之前的情况?

最佳答案

(c = a * b)!=(a = c + a); 调用未定义的行为。表达式 (c = a * b)(a = c + a) 的求值顺序未排序。

C11-6.5/2:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.[...]

报价

The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments.

表示对于a = b;a += b这样的表达式,将b赋值给a 在两个语句中的子表达式 ab 求值之后排序。这是由 C 标准保证的。但是,不保证上述语句中 ab 的计算顺序。

关于c - C中的关系运算符有固定的求值顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521654/

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