&之间的差异和&&在C中? [英] Difference between & and && in C?

查看:59
本文介绍了&之间的差异和&&在C中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C语言中的& & 有什么区别?

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);

输出:

a & b = 0;
a && b = 1;

我不确定为什么在一种情况下会返回true,而在另一种情况下会返回false.

I'm not sure why this would return true in one scenario and false in another.

推荐答案

& 按位,& 逻辑和.

表达式 x&&如果 x y 都不为零,则y 将返回 1 ,否则返回 0 .请注意,如果 x 为零,则将完全不评估 y .如果 y 是带有副作用的表达式,这将很重要.

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. This will matter if y is an expression with side effects.

表达式 x&y 将对 x y 中的每个单独的位执行按位运算.因此,如果 x 是二进制代码 1010 ,而 y 1100 ,则 x&y 的值为 1000 .请注意, x&y 不应解释为布尔值.

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.

还要注意,尽管直觉说应该与之相反,但& 的优先级却比& 低.比较运算符也是如此,例如< < = == != > = > .这可以追溯到C没有运算符&& || 的时候,而是使用按位版本.此时,这是有道理的,但是当添加逻辑运算符时,它不再存在.Kernighan和Ritchie承认这样做会更有意义,但他们没有解决它,因为这会破坏现有代码.

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.

我不确定为什么在一种情况下会返回true,而在另一种情况下会返回false.

I'm not sure why this would return true in one scenario and false in another.

x&的返回值y 根本不应该被视为布尔值.但是,可以(取决于代码的编写方式)将其视为布尔数组.如果您有两个整数,分别是 flags1 flags2 ,则 flags1&的结果为flags2 将表示在两者 flags1 flags2 中都切换了哪些标志.

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.

这篇关于&amp;之间的差异和&amp;&amp;在C中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆