c++ - 你可以在 C++ 中按位移动 bool 值吗?

标签 c++ bit-shift

我正在使用其他人的代码,该代码是用较旧的编译器编写的,该编译器映射了一个特殊的 BOOL输入 unsigned int ,但在我的编译器中它被映射到一个真正的 bool .在他的代码中的某些地方,他使用了位移运算符 <<bool type,这是我以前从未见过的,当我的编译器没有提示时,我感到很惊讶。

那是有效的 C++ 吗? bool自动晋升为 intuint ?

我看到了this related question ,这为另一个问题提供了一些清晰度,但它没有解决移位运算符。

最佳答案

来自移位运算符 [expr.shift]

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand

bool 是一个整数类型,因此代码格式正确(bool 被提升为 int 并且结果是一个 int)。

来自 [conv.prom] ,我们展示了 bool 值被提升为哪些整数:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one

之后,类次正常运行。 (谢谢,@chris)

关于c++ - 你可以在 C++ 中按位移动 bool 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47439616/

相关文章:

c++ - 虚函数可以内联吗

c++ - 在二维指针 vector 中插入列的正确方法是什么?

C++ 如何阻止负数作为参数传递,其中需要无符号

c++ - 在 AngelScript 中使用全局函数

c - C 中的移位运算符(<<、>>)是算术运算符还是逻辑运算符?

c - 有符号整数的算术位移

c++ - const auto 和对象恒常性

c++ - 为什么将此位移至 51

c# - .Net 4.6 打破 XOR 密码模式?

c - 按类型宽度移位不返回零