在 C++ 中对布尔值使用位运算符
在 C++ 中是否有任何理由不使用位运算符 &、| 和 ^ 来表示布尔"值?
Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++?
我有时会遇到我希望两个条件之一为真(XOR)的情况,所以我只是将 ^ 运算符放入条件表达式中.我有时还希望评估条件的所有部分是否为真(而不是短路),所以我使用 &和|.有时我还需要累积布尔值,&= 和 |= 非常有用.
I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.
执行此操作时,我引起了一些人的注意,但代码仍然比其他情况下更有意义且更简洁.有什么理由不将这些用于布尔值吗?是否有任何现代编译器对此给出不好的结果?
I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?
推荐答案
||
和 &&
是布尔运算符,内置的保证返回 true
或 false
.没有别的了.
||
and &&
are boolean operators and the built-in ones are guaranteed to return either true
or false
. Nothing else.
|
、&
和 ^
是按位运算符.当你操作的数字域只是 1 和 0 时,它们是完全相同的,但在你的布尔值不是严格意义上的 1 和 0 的情况下–就像 C 语言一样 –您最终可能会遇到一些您不想要的行为.例如:
|
, &
and ^
are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance:
BOOL two = 2;
BOOL one = 1;
BOOL and = two & one; //and = 0
BOOL cand = two && one; //cand = 1
然而,在 C++ 中,bool
类型只能保证为 true
或 false
(分别隐式转换为 1
和 0
),所以这种立场不那么担心,但人们不习惯在代码中看到这样的事情这一事实为不这样做提供了一个很好的论据它.只需说 b = b &&x
并完成它.
In C++, however, the bool
type is guaranteed to be only either a true
or a false
(which convert implicitly to respectively 1
and 0
), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x
and be done with it.
相关文章