What is the difference between &
and &&
in C?
我的老师给了我这个例子:
int a = 8;
int b = 4;
printf("a & b = %d\n", a & b);
printf("a && b = %d\n", a && b);
输出:
a & b = 0;
a && b = 1;
我不确定为什么在一种情况下会返回true,而在另一种情况下会返回false。
What is the difference between &
and &&
in C?
我的老师给了我这个例子:
int a = 8;
int b = 4;
printf("a & b = %d\n", a & b);
printf("a && b = %d\n", a && b);
输出:
a & b = 0;
a && b = 1;
我不确定为什么在一种情况下会返回true,而在另一种情况下会返回false。
&
is bitwise and and&&
is logical and.The expression
x && y
will return1
if bothx
andy
is non-zero, and0
otherwise. Note that ifx
is zero, theny
will not be evaluated at all.The expression
x & y
will perform a bitwise operation on each individual bit inx
andy
. So ifx
is1010
in binary andy
is1100
thenx & y
will evaluate to1000
. Note that the return value ofx & y
should NOT be interpreted as a Boolean value.One way to explain it is that you could imagine that
&
is the same thing as applying&&
on each individual bit in the operands.Also note that
&
has lower precedence than&&
, even though intuition says that it should be the other way around. This also goes for comparison operators, like<
,<=
,==
,!=
,>=
,>
. This goes back to the time when C did not have the operators&&
and||
and the bitwise versions was used instead. At this time, it made sense, but when the logical operators were added, it did not anymore. Kernighan and Ritchie admitted that it would have made more sense, but they did not fix it because this would break existing code.The return value from
x & y
should not be treated as a Boolean value at all. However, it can (depending on how the code is written) be treated as a Boolean array. If you have two integers,flags1
andflags2
then the result offlags1 & flags2
will denote which flags that are toggled in bothflags1
andflags2
.The
&
operator performs a bit-wise and operation on its integer operands, producing an integer result. Thus(8 & 4)
is(0b00001000 bitand 0b00000100)
(using a binary notation that does not exist in standard C, for clarity), which results in0b00000000
or0
.The
&&
operator performs a logical and operation on its boolean operands, producing a boolean result. Thus(8 && 4)
is equivalent to((8 != 0) and (4 != 0))
, or(true and true)
, which results intrue
.>
In your teacher's example
a && b
, the left operand4
and the right operand8
are both non-zero. So the condition will become true.In your teacher's other example
a & b
, the left operand4
or0100
and the right operand8
or01000
copies no bits to the result. This is because there are no common set bits in either operand.