Is there any difference between amp;amp; and amp; with bool(s)?(amp;amp; 之间有什么区别吗?和amp;与布尔(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;
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 Integral conversions
...
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.
So the effect in the example you give is guaranteed to be the same and is 100% portable.
For the case you give, any decent compiler is likely to generate identical (optimal) code.
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.
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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:&& 之间有什么区别吗?和&与布尔(S)?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07