布尔 AND 和 OR 运算
为什么下面的代码输出1
,而不是0
? 一个 || b
应该给我 1
和 1 && 0
是 0
,对吗?我不认为逻辑运算是从右到左评估的。
int main()
{
printf("%d\n", 1 || 1 && 0);
return 0;
}
Why does the following code output 1
, instead of 0
? a || b
should give me 1
and 1 && 0
is 0
, right? I don't think logical operations evaluated from right to left.
int main()
{
printf("%d\n", 1 || 1 && 0);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
&&
的优先级高于||
。 (就像乘法的优先级高于加法一样。)&&
has higher precedence than||
. (Like how multiplication has higher precedence than addition.)这是因为运算符优先级。在 C 语言中,&&运算符的优先级高于||运算符,因此首先对其进行评估。
This is because of operator precedence. In C, the && operator has higher precedence than the || operator so it is evaluated first.
这来自逻辑思维的发展(布尔算术),甚至可能来自使用晶体管-晶体管-逻辑和较低级硬件语言(例如 VHDL)的硬件设计。我们通常做两层逻辑,第一层是“与”,第二层是“或”。最典型的情况是电路最小化[1]。
通常,您可以将输入信号组合组合为 AND 端口输入,并将 AND 端口输出组合为 OR 端口输入。
[1] http://en.wikipedia.org/wiki/Circuit_minimization
This comes from logical thinking development (boolean arithmetic), maybe even from hardware design using transistor-transistor-logic and lower level hardware languages (VHDL, for instance). We usually do two layer logics, first layer of AND's and second of OR's. The most typical situation being circuit minimization [1].
Typically, you combine input signals combinations as AND-ports inputs, and AND-ports outputs as OR-port inputs.
[1] http://en.wikipedia.org/wiki/Circuit_minimization