tilde operator returning -1, -2 instead of 0, 1 respectively(波浪号运算符分别返回 -1、-2 而不是 0、1)
问题描述
我对此感到有些困惑.我认为 C++ 中的 ~ 运算符应该以不同的方式工作(不是 Matlab-y).这是一个最小的工作示例:
I'm kind of puzzled by this. I thought the ~ operator in C++ was supposed to work differently (not so Matlab-y). Here's a minimum working example:
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
bool banana = true;
bool peach = false;
cout << banana << ~banana << endl;
cout << peach << ~peach << endl;
}
这是我的输出:
1-2
0-1
我希望有人对此有所了解.
I hope someone will have some insight into this.
推荐答案
这正是应该发生的事情:当你反转零的二进制表示时,你得到负一;当你反转一的二进制表示时,你会在二进制补码表示中得到负二.
This is exactly what should happen: when you invert the binary representation of zero, you get negative one; when you invert binary representation of one, you get negative two in two's complement representation.
00000000 --> ~ --> 11111111 // This is -1
00000001 --> ~ --> 11111110 // This is -2
请注意,即使您以 bool
开头,运算符 ~
也会根据整数规则将值提升为 int
促销.如果您需要将 bool
反转为 bool
,请使用运算符 !
而不是 ~
.
Note that even though you start with a bool
, operator ~
causes the value to be promoted to an int
by the rules of integer promotions. If you need to invert a bool
to a bool
, use operator !
instead of ~
.
这篇关于波浪号运算符分别返回 -1、-2 而不是 0、1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:波浪号运算符分别返回 -1、-2 而不是 0、1


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01