gpt4 book ai didi

c++ - && 运算符的交换属性问题

转载 作者:太空狗 更新时间:2023-10-29 23:48:42 26 4
gpt4 key购买 nike

下面我一直遇到奇怪问题的代码旨在删除整数数组中未使用的部分,然后将其转换为字符串。

例如:_ABC__DE______ 将变为 _ABC__DE

当输入填充默认字符时出现问题。 (示例中的“_”)。

sLength是整型数组chars

的长度

有问题的代码:

  int inputLength = sLength - 1;

while (chars[inputLength] == defaultChar && inputLength >= 0) {
inputLength--;
}

inputLength++;

Serial.println("input length: " + String(inputLength));
// (in)sanity check
Serial.println(inputLength);
Serial.println(String(inputLength));
Serial.println(inputLength <= 0);
Serial.println(0 <= 0);
Serial.println(inputLength == 0);
Serial.println(0 == 0);

if (inputLength <= 0) {
//reset cursor position
Serial.println("index set to 0");
index = 0;
} else {
output = "";
for (int i = 0; i < inputLength; i++) {
char c = charSet[chars[i]];
if (c == '_') {
c = ' ';
}
output += c;
}
done = true;
}

给定一个用 defaultChar 填充的数组时的输出:

input length: 0
0
0
0
1
0
1

如果我解释正确,输出意味着偶数行上 0 > 0 和 0 =/= 0,但奇数行上 0 <= 0 和 0 = 0。


我想到的解决方法是替换

  while (chars[inputLength] == defaultChar && inputLength >= 0) {
inputLength--;
}

具有以下之一

  while (inputLength >= 0 && chars[inputLength] == defaultChar) {
inputLength--;
}

.

  while (chars[inputLength] == defaultChar) {
inputLength--;
if (inputLength < 0) {
break;
}
}

两者的输出都是:

input length: 0
0
0
1
1
1
1
index set to 0

为什么这会改变结果?据我所知,&& 运算符是可交换的。

有什么我遗漏的东西吗

chars[inputLength] == defaultChar && inputLength >= 0

不等于

inputLength >= 0 && chars[inputLength] == defaultChar?

如果相关的话,这是在 328P Arduino Nano 上运行的,旧的引导加载程序使用 IDE 1.8.8

最佳答案

&& 不可交换。它首先评估左操作数,然后在左操作数评估为 0 时停止。

您的原始代码失败是因为在某些时候它计算了 chars[-1](如果 chars 是一个数组,这将导致 undefined behaviour)。替代版本没有这个问题,因为它在使用 inputLength 作为数组索引之前执行 >= 0 测试。

关于c++ - && 运算符的交换属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54803358/

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