gpt4 book ai didi

C++ 与赋值表达式的比较是右侧表达式

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

我目前正在处理一个关于使用 C++ 的数据结构的问题。我将检查单向链表中的节点是否按升序排序。这是我的代码的一些细节

节点.cpp

class Node
{
public:
double data;
Node* next;
};

对于出现问题的部分,

double preValue = sLL.head->data;       
Node *curNode = sLL.head->next;

do
{
if (preValue > (preValue = curNode->data)) // Problem occur in this line
return false;
}while (curNode = curNode->next);

因为“>”运算符的求值顺序是先求左手边的表达式,然后再求右手边的表达式

赋值运算符将返回左值的引用。

因此,preValue>(preValue = curNode->data)应该比较上一个节点和当前节点,比较完成后赋值下一个节点的数据。因此,我认为我的实现应该是有效的。

然而,if(preValue > (preValue = curNode->data)) 的结果出乎我的意料新的 preValue,它一直返回 false。

我试图打印出 if 语句的返回值,只要左边的表达式大于或小于右边的表达式,它总是返回 0。我不明白为什么会这样。谁能告诉我我犯了什么错误?

附注该程序在以下实现中运行良好

double preValue = list.head->data;      
Node *curNode = list.head->next;

do
{
if (preValue > curNode->data) // Check ascending order
return false;

preValue = curNode->data;

}while (curNode = curNode->next);

最佳答案

这一行是未定义的行为:

if (preValue > (preValue = curNode->data))  // Problem occur in this line

因为您要分配给一个变量 (preValue) 并从同一个变量中读取,并且读取不用于确定写入的值

来自 C++03 §5/4 [expr]:

[...] 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.

sequence 点出现在完整表达式(即以分号结尾的表达式或语句)之后,以及 &&|| 的第一个操作数之后。 ?: 运算符。所有其他运算符(包括 > 运算符)在它们的参数求值之间有序列点。序列点也出现在其他一些与本题无关的地方。

如您所说,解决方法是将其分开,以便赋值发生在与比较不同的单独语句中。

当我使用带有 -Wall 编译器标志的 GCC 编译此代码时,我收到此警告:

warning: operation on ‘preValue’ may be undefined [-Wsequence-point]

我强烈建议您始终使用 -Wall-Werror 进行编译,以便编译器立即标记这些错误,您可以更正它们。

关于C++ 与赋值表达式的比较是右侧表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19689135/

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