C++ && 和 & 与 bool(s) 有什么区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6577504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:23:13  来源:igfitidea点击:

Is there any difference between && and & with bool(s)?

c++bitwise-operatorsbooleanlogical-operatorslanguage-lawyer

提问by WilliamKF

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

在 C++ 中,在 bool(s)之间执行&&(逻辑) 和&(按位) 之间有什么区别吗?

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

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

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

case1case2相同的,或者如果不相同,它们究竟如何变化,为什么要选择一个而不是另一个?按位和布尔值是否可移植?

回答by Nemo

The standardguarantees that falseconverts to zero and trueconverts to one as integers:

标准保证false转换为零并true转换为整数:

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.

4.7 积分转换

...

如果目标类型是 bool,请参见 4.12。如果源类型为 bool,则值 false 转换为零,值 true 转换为 1。

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

所以你给出的例子中的效果保证是一样的,并且是 100% 可移植的。

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

对于您给出的情况,任何体面的编译器都可能生成相同(最佳)的代码。

However, for Boolean expressions expr1and expr2, it is not true in general that expr1 && expr2is the same as expr1 & expr2because &&performs "short-circuit" evaluation. That is, if expr1evaluates to false, expr2will not even be evaluated. This can affect performance (if expr2is complicated) and behavior (if expr2has 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.)

然而,对于布尔表达式expr1expr2,它不是一般的事实,expr1 && expr2是一样的expr1 & expr2,因为&&执行“短路”的评价。也就是说,如果expr1评估为falseexpr2甚至不会被评估。这会影响性能(如果expr2很复杂)和行为(如果expr2有副作用)。(但请注意,&如果避免条件分支,表单实际上可以更快......出于性能原因玩弄这种东西几乎总是一个坏主意。)

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.

在我看来,除非你特别依赖于“短路”行为,否则你应该选择最能清楚表达你的意图的表述。所以&&用于逻辑 AND 和&位运算 AND ,任何有经验的 C++ 程序员都会发现你的代码很容易理解。

回答by Richard Schneider

When using logical and &&, the right-hand expression will not be evaluated if the left-hand expression is false.

使用逻辑 and 时&&,如果左侧表达式为假,则不会计算右侧表达式。

A lot of C/C++/C# code relies on this, as in: if (p != null && p->Foo()).

许多C / C ++ / C#代码依赖于这一点,如在:if (p != null && p->Foo())

For your example I would use case2 (logical and). Only use bitwise when dealing with bit flags, etc.

对于您的示例,我将使用 case2(逻辑与)。仅在处理位标志等时使用按位。

However, if foo() and bar() only return bool (0, 1) then case1 and case2 are the same.

然而,如果 foo() 和 bar() 只返回 bool (0, 1) 那么 case1 和 case2 是一样的。

回答by Hot Licks

There is a difference (well, two), though you wouldn't see it in your example.

有区别(好吧,两个),尽管您不会在示例中看到它。

"&" does a bitwise "AND" operation, meaning that 0x1 & 0x1 = 0x1, but 0x1 & 0x2 = 0x0. OTOH, "&&" is a boolean/logical "AND", meaning it treats any non-zero value as a TRUE, so 0x1 && 0x1 = TRUE(which is generally represented as -1, ie, all ones [or maybe it's represented as 1 in C++, I forget]), while 0x1 && 0x2 = TRUEas well.

"&" 执行按位 "AND" 运算,这意味着0x1 & 0x1 = 0x1, 但是0x1 & 0x2 = 0x0. OTOH,“&&”是一个布尔值/逻辑“AND”,这意味着它将任何非零值视为 TRUE,因此0x1 && 0x1 = TRUE(通常表示为 -1,即全 1 [或者可能在 C++ 中表示为 1,我忘记了]),同时0x1 && 0x2 = TRUE也是。

In addition, "&&" is short-circuiting, meaning that if the first operand is FALSE, the second won't be evaluated. So, while FALSE & null_pointer->booleanField ==> null pointer exception, FALSE && null_pointer->booleanField = FALSE.

此外,“&&”是短路的,这意味着如果第一个操作数为 FALSE,则不会评估第二个操作数。所以,虽然FALSE & null_pointer->booleanField ==> null pointer exceptionFALSE && null_pointer->booleanField = FALSE

There may be a slight performance advantage in using bitwise operations in some cases, but generally you should use the double forms when evaluating boolean values, so that your code is independent of the precise representation of boolean TRUE and FALSE.

在某些情况下使用按位运算可能会有轻微的性能优势,但通常您应该在评估布尔值时使用双精度形式,以便您的代码独立于布尔值 TRUE 和 FALSE 的精确表示。

回答by mah

Algorithmically there's no difference, however use of && allows you to "short circuit" the check. That is, to decide case2, if val1 is false then the compiled code has no reason to check the value of val2 in order to determine the answer, where case1 requires the actual AND to take place.

算法上没有区别,但是使用 && 允许您“短路”检查。也就是说,要确定 case2,如果 val1 为假,则编译后的代码没有理由检查 val2 的值以确定答案,其中 case1 需要发生实际的 AND。

Realistically, a good compiler will recognize this and produce the same code... it comes down to how good your compiler is.

实际上,一个好的编译器会认识到这一点并生成相同的代码……这取决于您的编译器有多好。

回答by makiSTB

"&&" is a "conditional logical "AND" it evaluates the second expression ONLY if the first is TRUE

&&”是一个“条件逻辑“AND”,它仅在第一个表达式为 TRUE 时才对第二个表达式求值

"&" is a "non-conditional logical AND" <-- (if you are playing with boolean expressions) it evaluates both expression

&”是“非条件逻辑与”<--(如果您正在使用布尔表达式)它会评估两个表达式



MOREOVER"&" is a 'bitwise' operator that means it operates on a bit-level.

此外,“&”是一个“按位”运算符,这意味着它在位级别上进行操作。

This example can make you understand better.

这个例子可以让你更好地理解。

4 = 00000100  // 'four' bit set
5 = 00000101  // 'four' bit and 'one' bit set

00000100 (4) & // AND: only keep bits set in both
00000101 (5)
--------
00000100 (4)

00000100 (4) | // OR: keep bits set in either
00000101 (5)
--------
00000101 (5)

00000100 (4) ^ //  EXCLUSIVE OR: keep bits only set in one but not the other
00000101 (5)
--------
00000001 (1)

回答by Javeria

The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise.

逻辑运算符 && 和 || 在评估两个表达式以获得单个关系结果时使用。运算符 && 对应于布尔逻辑运算 AND。如果它的两个操作数都为真,则此操作的结果为真,否则为假。

The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves.

运算符 || 对应于布尔逻辑运算 OR。如果其两个操作数中的任何一个为真,则此操作的结果为真,因此仅当两个操作数本身都为假时才为假。

回答by Shuvo Sarker

int a = 0, b = 10;

if(a == 1 && (b/a) == 0) cout << "This is okay\n"; // the 2nd expression is never checked as the first one is false

cout << "Bingo\n";

if(a == 1 & (b/a) == 0) cout << "This is not okay\n"; // program crashes here trying to divide by zero

cout << "Bingo\n"; // this will never get printed