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
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
