问题
What is the difference between &
and &&
in C?
My teacher gave me this example:
int a = 8;
int b = 4;
printf("a & b = %d\n", a & b);
printf("a && b = %d\n", a && b);
Output:
a & b = 0;
a && b = 1;
I'm not sure why this would return true in one scenario and false in another.
回答1:
&
is bitwise and and &&
is logical and.
The expression x && y
will return 1
if both x
and y
is non-zero, and 0
otherwise. Note that if x
is zero, then y
will not be evaluated at all.
The expression x & y
will perform a bitwise operation on each individual bit in x
and y
. So if x
is 1010
in binary and y
is 1100
then x & y
will evaluate to 1000
. Note that the return value of x & 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.
I'm not sure why this would return true in one scenario and false in another.
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
and flags2
then the result of flags1 & flags2
will denote which flags that are toggled in both flags1
and flags2
.
回答2:
&& (logical and operator) - The left and right operands are
boolean
expressions. If both the operands are non-zero, then the condition becomes true.
>
& (bitwise and operator) - The left and right operands are
integral
types. Binary AND Operator copies a bit to the result if it exists in both operands.
In your teacher's example a && b
, the left operand 4
and the right operand 8
are both non-zero. So the condition will become true.
In your teacher's other example a & b
, the left operand 4
or 0100
and the right operand 8
or 01000
copies no bits to the result. This is because there are no common set bits in either operand.
回答3:
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 in 0b00000000
or 0
.
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 in true
.
来源:https://stackoverflow.com/questions/49617159/difference-between-and-in-c