平等运算符优先级不起作用
Equality operator precedence not working
在 C++ 中,相等运算符的结合性是从左到右的,如 here and here and the returned value of an assignment operation is the value assigned to the given variable. (As shown here, here, here, and here 所述(第 6.5.16 节,第 101-104 页最后 link)。)
根据此信息,这:
double d = 5;
if (d == (d = 6))
cout << "but d was 5...!!!" << endl;
else
cout << "5!=6 :)" << endl;
应该打印 "5!=6 :)"
因为表达式 (d == (d = 6))
等同于 (5 == (6))
(这是错误的),而是打印 "but d was 5..."
。谁能解释一下为什么?
您将关联性与求值顺序混淆了。
从左到右的结合性意味着
a == b == c
被解释为
(a == b) == c
这与 a == b
等表达式中术语的求值顺序无关。编译器可以按任何顺序自由计算 a
和 b
。因此,在您的情况下,编译器可以先自由评估 d
或先评估 (d = 6)
。因此,您的程序可以评估为 true
或 false
,具体取决于首先评估运算符的哪一侧。如果存在竞争条件(编译器也可以自由地并行评估它们),结果将不同于一个 运行 下一个。
标准的相关部分是这样的:
[intro.execution]/15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. 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, and they are not potentially concurrent (1.10), the behavior is undefined.
强调我的。您的程序表现出未定义的行为,因为 d
的修改(在比较的右侧)与 d
的值计算(在比较的左侧)未排序。关联性和优先级不在此范围内。
在 C++ 中,相等运算符的结合性是从左到右的,如 here and here and the returned value of an assignment operation is the value assigned to the given variable. (As shown here, here, here, and here 所述(第 6.5.16 节,第 101-104 页最后 link)。)
根据此信息,这:
double d = 5;
if (d == (d = 6))
cout << "but d was 5...!!!" << endl;
else
cout << "5!=6 :)" << endl;
应该打印 "5!=6 :)"
因为表达式 (d == (d = 6))
等同于 (5 == (6))
(这是错误的),而是打印 "but d was 5..."
。谁能解释一下为什么?
您将关联性与求值顺序混淆了。
从左到右的结合性意味着
a == b == c
被解释为
(a == b) == c
这与 a == b
等表达式中术语的求值顺序无关。编译器可以按任何顺序自由计算 a
和 b
。因此,在您的情况下,编译器可以先自由评估 d
或先评估 (d = 6)
。因此,您的程序可以评估为 true
或 false
,具体取决于首先评估运算符的哪一侧。如果存在竞争条件(编译器也可以自由地并行评估它们),结果将不同于一个 运行 下一个。
标准的相关部分是这样的:
[intro.execution]/15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. 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, and they are not potentially concurrent (1.10), the behavior is undefined.
强调我的。您的程序表现出未定义的行为,因为 d
的修改(在比较的右侧)与 d
的值计算(在比较的左侧)未排序。关联性和优先级不在此范围内。