为什么c ++对布尔不具有&&& =或|| =? [英] Why doesn't c++ have &&= or ||= for booleans?
问题描述
是否有可能发生的非常糟糕的事情&& =和|| =被用作语法糖 bool foo = foo&&& bar
and bool foo = foo || bar
?
Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for bool foo = foo && bar
and bool foo = foo || bar
?
推荐答案
A bool
只有C ++中的 true
或 false
。因此,使用& =
和 | =
是完全安全的不特别喜欢的符号)。真的,他们将执行位操作而不是逻辑操作(因此,它们不会短路),但是这些位操作遵循良好定义的映射,这有效地等同于逻辑操作, 两个操作数 确实是 bool
。
A bool
may only be true
or false
in C++. As such, using &=
and |=
is perfectly safe (even though I don’t particularly like the notation). True, they will perform bit operations rather than logical operations (and as such, they won’t short-circuit) but these bit operations follow a well-defined mapping, which is effectively equivalent to the logical operations, as long as both operands are indeed of type bool
.
与其他人在这里说的不同,C ++中的 bool
不能有不同的值,例如 2
。当将该值赋给 bool
时,它将根据标准转换为 true
。
Contrary to what other people have said here, a bool
in C++ must never have a different value such as 2
. When assigning that value to a bool
, it will be converted to true
as per the standard.
在 bool
中获取无效值的唯一方法是使用 reinterpret_cast
on pointer:
The only way to get an invalid value into a bool
is by using reinterpret_cast
on pointers:
int i = 2;
bool b = *reinterpret_cast<bool*>(&i);
b |= true; // MAY yield 3 (but doesn’t on my PC!)
未定义的行为,我们可以安全地忽略遵循C ++代码的这个潜在问题。
But since this code results in undefined behaviour anyway, we may safely ignore this potential problem in conforming C++ code.
这篇关于为什么c ++对布尔不具有&&& =或|| =?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!