有时我想做这样的事情(i 和 j 是整数)。
(if i==4 && j==9)
{
...
}
如果 i 等于 4 且 j 等于 9,它将通过方括号。我一直在使用单与号 (&) 而不是双一,并且我的代码一直在编译和运行。
它是否与双 && 做同样的事情,如果不是,它一直在做什么?
编辑:哦,我一直在用 or 做同样的事情,使用 '|' 而不是'||'
有时我想做这样的事情(i 和 j 是整数)。
(if i==4 && j==9)
{
...
}
如果 i 等于 4 且 j 等于 9,它将通过方括号。我一直在使用单与号 (&) 而不是双一,并且我的代码一直在编译和运行。
它是否与双 && 做同样的事情,如果不是,它一直在做什么?
编辑:哦,我一直在用 or 做同样的事情,使用 '|' 而不是'||'
Presumably you mean if (i==4 && j==9)
.
Under the circumstances, changing this from &&
to &
shouldn't change much. The big thing that'll change is that with &&
, the j==9
would only be evaluated if the i==4
part was true, but with &
, they'll both be evaluated regardless.
When you have something like if (x != NULL && x->whatever ...)
you want to ensure that the second part (that dereferences x
) is only evaluated if x
is not a null pointer. In your case, however, comparing what appear to be int
s is unlikely to produce any problems.
It's also possible to run into a problem when you're dealing with something that may produce a value other than 1
to signal true
. Again, it's not a problem here because ==
will always produce either 0
or 1
. If (for example) you were using isalpha
, islower
, etc., from <ctype.h>
, they're only required to produce 0
or non-zero values. If you combined those with a &
, you'd get a bit-wise or
which could produce 0 for two non-zero inputs (e.g., 1 & 2 == 0
, but 1 && 2 == 1
).
When you use bitwise and
on the results from ==
, you're going to get 0 & 0
or 0 & 1
or 1 & 0
or 1 & 1
. 1 & 1
will yield 1
(true). All the others will yield 0 (false) --- just like &&
would have.
它正在执行按位 AND。
它所做的是表达式i == 4
等价于1
if i
is4
并且对于 RHS 相同(显然带有j
and 9
)。&
运算符返回两个操作数都有该位的数字。
它的工作原理与&&
因为00000001 & 00000001
(例如缩小到一个字节)相同。如果一个是0
(条件为假),则&
不会看到两个操作数都打开了两个位,并且00000000
is 0
,这是falsey。
但是,不要简单地使用&
,因为它比一个字符短或相似。使用它,因为它表达了您想要实现的目标。如果它是您想要的逻辑 AND,请使用&&
.
同样的事情适用于|
,除了如果每个操作数都打开它而不是结果位,它会在任一操作数打开该位时打开它。
单个 & 符号执行按位与。仅当两个操作数在该位置都为 1 时,才会设置结果的每一位。
Since comparisons in C return 1 for true and 0 for false, &
will give the same results as &&
as long as both operands are comparisons. But for arbitrary values, it will return seemingly random results. 1 && 2
is true, but 1 & 2
is false because the binary representations of 1 and 2 have no bits in common.
单个&符号称为按位与。它是一个二进制运算符,逐位“与”两个数字。
例如,如果你有两个二进制数,01100010 和 00011111,你的按位和将导致 00000010
i==4 返回 1(真),j==9 也是如此。因此,i==4 & j==9 实际上只是 1 & 1,其计算结果为 1(真)。
试试这些例子看看有什么不同
1) 整数 k = 4 & 6; vs int k = 4 && 6;
2) if(i==4 && 2) 与 if(i==4 & 2)