XOR操作员未在C 中正确评估
XOR operator not evaluating correctly in C++
我正在从c 中从头开始建造一个bigint课程,但是有些东西使我发疯:我的XOR无法正常工作,我不知道为什么。我希望有人能启发我。以下是一个最小的工作示例:
class BigInt
{
private:
bool pos;
int size; // Number of binary digits to use
short compare(BigInt input);
public:
BigInt(long long input, int inSize) { pos = true; size = inSize; }
};
short BigInt::compare(BigInt input)
{
// Partial compare function for minimal working example
// Return:
// 1: (*this) > input
// 0: (*this) == input
// -1: (*this) < input
string a = (*this).toDecimal(), b = input.toDecimal();
bool c = (*this).size > input.size, d = (*this).pos ^ input.pos;
bool thispos = (*this).pos, inpos = input.pos;
bool xorpos = (thispos != inpos);
bool x = true, y = true;
bool z = x ^ y;
if ((*this).size > input.size || (*this).pos != input.pos)
return 1 - ((*this).pos ? 0 : 2);
else if ((*this).size < input.size)
return -1 + ((*this).pos ? 0 : 2);
return 0;
}
我在第一个if语句上有一个断点。以下是我在手表列表中的内容。
thispos true bool
inpos true bool
xorpos true bool
x true bool
y true bool
z false bool
有人知道发生了什么事吗?我宁愿避免掌握我的if声明。我从来没有如此简单的XOR使用问题。
据我所知,应该没有错,但是这些价值观有些东西不会评估它们的期望。
编辑:将代码更改为最小工作示例。
好吧,即使 ^
是位XOR操作员,您的初始化
bool thispos = (*this).pos, inpos = input.pos;
需要将源值转换为bool
类型。bool
类型的值可以保证在算术上下文中充当0
或1
。这意味着
bool xorpos = thispos ^ inpos;
如果thispos
和inpos
最初是true
。用false
初始化xorpos
。
如果您观察到不同的行为,则可能是编译器中的错误。积分到-bool
转换可能会错误地实现或类似的东西。
另一个机会是某人通过执行
之类的事情"重新定义"了bool
关键字 #define bool unsigned char
这将在第一对初始化中禁用适当的bool
语义,并导致^
的位性质影响结果。
为什么不简单地 x != y
?这也与您的类型更一致。
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- <<操作员在下面的行中工作
- c++11评估顺序(未定义的行为)
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 如何使用"equal to"以外的评估编写开关语句
- 嵌套 if 中没有返回评估
- 懒惰的参数评估try_emplace?
- 在实践中,在运行时为零的乘法中是否有任何"lazy"评估
- 比根<操作员
- SFINAE不能防止模棱两可的操作员过载吗?
- C++操作员订单评估
- C const char *评估操作员超载
- C 评估表达操作员优先级不起作用
- XOR操作员未在C 中正确评估
- 操作员评估
- 操作员评估指令后
- 停止评估操作员<<