有间及放任何区别;放大器&;和&安培;与布尔(S)? [英] Is there any difference between && and & with bool(s)?

查看:152
本文介绍了有间及放任何区别;放大器&;和&安培;与布尔(S)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,有没有做任何区别&放大器;&安培; (逻辑)和&安培; (按位)布尔(S)之间?

In C++, is there any difference between doing && (logical) and & (bitwise) between bool(s)?

bool val1 = foo();
bool val2 = bar();

bool case1 = val1 & val2;
bool case2 = val1 && val2;

案例1 案例2 相同或者不究竟是如何做的,他们各不相同,为什么有人选择一个比其他?是和的bool的按位便携式?

Are case1 and case2 identical or if not how exactly do they vary and why would one choose one over the other? Is a bitwise and of bools portable?

推荐答案

标准保证转换成零和真正转换成一个作为整数

The standard guarantees that false converts to zero and true converts to one as integers:

4.7积分转换

...

如果目的地类型为布尔,见4.12。如果源类型是布尔,值假被转换到零,真值转换为一。

If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one.

因此​​,在你给保证是相同的,并且是示例的效果100%便携式

So the effect in the example you give is guaranteed to be the same and is 100% portable.

有关你给的情况下,任何像样的编译器可能会产生相同的(最佳)code。

For the case you give, any decent compiler is likely to generate identical (optimal) code.

不过,对于布尔前pressions 表达式1 表达式2 ,它不是一般的,真正的表达式1&放大器;&安培;表达式2 相同表达式1&放大器;表达式2 ,因为&放大器;&安培; 进行短路的评价。也就是说,如果表达式1 计算结果为表达式2 将甚至没有进行评估。这可能会影响性能(如表达式2 复杂)和行为(如表达式2 有副作用)。 (但请注意,&安培; 表其实是可以更快,如果它避免了条件分支......有了这样的性能方面的原因玩弄的东西几乎总是一个坏主意。 )

However, for Boolean expressions expr1 and expr2, it is not true in general that expr1 && expr2 is the same as expr1 & expr2 because && performs "short-circuit" evaluation. That is, if expr1 evaluates to false, expr2 will not even be evaluated. This can affect performance (if expr2 is complicated) and behavior (if expr2 has side-effects). (But note that the & form can actually be faster if it avoids a conditional branch... Toying with this sort of thing for performance reasons is almost always a bad idea.)

所以,你给具体的例子,在那里你将值加载到本地变量,然后对它们进行操作,行为是相同的,表现很可能是。

So, for the specific example you give, where you load the values into local variables and then operate on them, the behavior is identical and the performance is very likely to be.

在我看来,除非你是专门依靠短路的行为,你应该选择最清楚的前presses你的意图的制定。因此,使用&放大器;&安培; 的逻辑与和&安培; 对位变换AND,任何有经验的C ++程序员找到你的code容易。

In my opinion, unless you are specifically relying on the "short-circuit" behavior, you should choose the formulation that most clearly expresses your intention. So use && for logical AND and & for bit-twiddling AND, and any experienced C++ programmer will find your code easy to follow.

这篇关于有间及放任何区别;放大器&;和&安培;与布尔(S)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆