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。

- 积分

**0** - 话题

**0** - 评论

**3145** - 注册排名

**1848**

`&`

isbitwise andand`&&`

islogical 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.The return value from

`x & y`

shouldnotbe 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 inboth`flags1`

and`flags2`

.The

`&`

operator performs abit-wise andoperation 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 alogical andoperation 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`

.>

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.