gpt4 book ai didi

c++ - `C == C++` 是未定义的行为吗?

转载 作者:可可西里 更新时间:2023-11-01 18:20:03 26 4
gpt4 key购买 nike

一个 friend 告诉我:

int C = anything;

C == C++将具有值 true .这是一个玩笑,是对经常声称的“C 与 C++ 不同”的一种反驳。

但是,由于 ==不是序列点,我认为这实际上是未定义的行为。该程序可能首先评估 C++ ,所以 C > C++C == C++都是未定义的。然而,C >= C++将始终评估为真。当然,翻转操作数时也是如此(C++ <= C 始终为真,其他所有内容均未定义)。

这个分析是否正确?

最佳答案

所有情况都导致undefined behavior和不可预测的结果。

draft C++11 standard告诉我们,除非另有说明,否则操作数的求值顺序是无序的,并且如果同一个标量对象被 unseqeucend 副作用修改超过一次,那么我们就会有未定义的行为。如果我们需要修改对象并且必须为另一个操作数计算对象的值,它也是未定义的。这包含在 C++11 标准草案 1.9

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

5.9 Relational operators5.10 Equality operators 部分中的相等运算符或关系运算符均未指定顺序为操作数。

clang 也为这种情况提供警告,默认情况下,它应该类似于以下内容 ( see it live ):

 warning: unsequenced modification and access to 'C' [-Wunsequenced]
if( C == C++ )
~ ^

这也是 C++03 中未定义的行为,没有使用排序关系的概念,而只是 sequence points .在 C++03 标准草案中,相关部分将是 第 5 章 Expressions,其中说:

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.57) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

这更容易推理,因为在同一序列点内多次修改或修改和使用标量的值是未定义的行为,而无需弄清楚操作的顺序。

关于c++ - `C == C++` 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25965372/

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