之间的区别和|| ,或&和&& [英] Difference between | and || , or & and &&
问题描述
这些是用Dev-cpp C ++ 5.4.2编写的C ++中的两个简单示例:
These are two simple samples in C++ written on Dev-cpp C++ 5.4.2:
float a, b, c;
if (a | b & a | c)
printf("x = %.2f\tF = %.0f\n", x, F);
else
printf("x = %.2f\tF = %.2f\n", x, F);
和以下代码:
float a, b, c;
if (a || b && a || c)
printf("x = %.2f\tF = %.0f\n", x, F);
else
printf("x = %.2f\tF = %.2f\n", x, F);
有人可以告诉我 ||
之间的区别> |
和&
> & 。第二个代码有效,但第一个无效。
并且编译器给出错误消息:
Can somebody tell my difference between ||
> |
and &
> &&
. The second code works , but first does not.
And compiler gives an error message :
[错误]类型为'float'和'float'的无效操作数为二进制'
[Error] invalid operands of types 'float' and 'float' to binary 'operator&'.
推荐答案
运算符 |
,&
和〜
并行作用于各个位。它们只能用于整数类型。 a | b
对 a
的每个位与相应的 b
的位进行独立的或运算生成结果的那一部分。
The operators |
, &
, and ~
act on individual bits in parallel. They can be used only on integer types. a | b
does an independent OR operation of each bit of a
with the corresponding bit of b
to generate that bit of the result.
运算符 ||
,&&
,和!
对每个整个操作数进行操作,作为单个 true
/ false
值。可以使用任何隐式转换为 bool
的数据类型。许多数据类型,包括 float
都隐式转换为bool,它暗含了!= 0
操作。
The operators ||
, &&
, and !
act on each entire operand as a single true
/false
value. Any data type can be used that implicitly converts to bool
. Many data types, including float
implicitly convert to bool with an implied !=0
operation.
||
和&
也短路。这意味着只要第一个操作数就可以确定结果的值,则第二个操作数就不会被评估。示例:
||
and &&
also "short circuit". That means whenever the value of the result can be determined by just the first operand, the second is not evaluated. Example:
ptr&& (* ptr == 7)
如果 ptr
为零,则结果为假,而不会因引用零而导致段错误。
ptr && (*ptr==7)
If ptr
is zero, the result is false without any risk of seg faulting by dereferencing zero.
您可以将其与(int)ptr& (* ptr)
。忽略这样一个事实,即使(int)ptr
为零,整个结果也将为零,所以人类可能会认为您不希望这样做。在这种情况下,不需要第二个操作数。但是该程序仍然可能会计算两者。
You could contrast that with (int)ptr & (*ptr)
. Ignoring the fact that this would be a bizarre operation to even want, if (int)ptr
were zero, the entire result would be zero, so a human might think you don't need the second operand in that case. But the program will likely compute both anyway.
这篇关于之间的区别和|| ,或&和&&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!