你能在 C++ 中按位移动 bool 吗?
Can you bitwise shift a bool in C++?
我正在使用其他人的代码,这些代码是用旧编译器编写的,该编译器将特殊的 BOOL
类型映射到 unsigned int
,但在我的编译器中它映射到真正的 bool
.在他的代码中的某些地方,他在 bool
类型上使用了移位运算符 <<
,这是我以前从未见过的,我的编译器没有报错让我感到惊讶。
那是有效的 C++ 吗? bool
会自动升级为 int
或 uint
吗?
我看到了 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] 开始,我们展示了布尔值被提升为哪些整数:
A prvalue of type bool
can be converted to a prvalue of type int
, with false
becoming zero and true becoming one
之后,班次表现正常。 (谢谢,@chris)
bool 移位的结果类型总是 int,不管右边是什么。
值得对其他人指出的内容进行一些解释:按位移动 bool
被转换为 int
。
bool b = true;
bool d = b << 1;
printf("%d\n", d);
此代码片段在屏幕上打印 1
而不是 0
。原因是 b << 1
被强制转换为 int
,即 2
(二进制 10
)。然后将结果转换为 bool
。如果 int
的值为 0
,则后一种转换为 0
,否则为 1
。由于 int
的值为 2
,因此 d
存储 1
.
布尔值移位的正确方法是按位使用 AND
(&
) 和 true
(1
).
bool d = (b << 1) & 1;
此 AND
操作强制将左侧转换为 bool
。
我正在使用其他人的代码,这些代码是用旧编译器编写的,该编译器将特殊的 BOOL
类型映射到 unsigned int
,但在我的编译器中它映射到真正的 bool
.在他的代码中的某些地方,他在 bool
类型上使用了移位运算符 <<
,这是我以前从未见过的,我的编译器没有报错让我感到惊讶。
那是有效的 C++ 吗? bool
会自动升级为 int
或 uint
吗?
我看到了 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] 开始,我们展示了布尔值被提升为哪些整数:
A prvalue of type
bool
can be converted to a prvalue of typeint
, withfalse
becoming zero and true becomingone
之后,班次表现正常。 (谢谢,@chris)
bool 移位的结果类型总是 int,不管右边是什么。
值得对其他人指出的内容进行一些解释:按位移动 bool
被转换为 int
。
bool b = true;
bool d = b << 1;
printf("%d\n", d);
此代码片段在屏幕上打印 1
而不是 0
。原因是 b << 1
被强制转换为 int
,即 2
(二进制 10
)。然后将结果转换为 bool
。如果 int
的值为 0
,则后一种转换为 0
,否则为 1
。由于 int
的值为 2
,因此 d
存储 1
.
布尔值移位的正确方法是按位使用 AND
(&
) 和 true
(1
).
bool d = (b << 1) & 1;
此 AND
操作强制将左侧转换为 bool
。