简体   繁体   English

c中的逻辑AND和OR

[英]logical AND and OR in c

In a && b , this returns true if both a and b are equal to 1. If a=-1 and b=-1 then also the expression returns true.Similar is the case with a||b,where a=-1 and b=0,it returns true. 在a && b中,如果a和b都等于1,则返回true。如果a = -1且b = -1,则表达式也返回true。类似于|| b,其中a = -1并且b = 0,它返回true。 Can anybody please explain the reason. 任何人都可以解释一下原因。

a && b returns 1 when both a and b are nonzero , not just when they're equal to 1. Otherwise it returns 0. a && b返回1当两个 ab非零的 ,不只是当他们等于1,否则返回0。

a || b a || b returns 1 when at least one of a or b is nonzero , not just when one of them is equal to 1. Otherwise it returns 0. ab 中的至少一个 非零 a || b返回1,而不仅仅是当其中一个等于1.否则返回0。

To give some examples: 举一些例子:

   0 &&  0 -> 0
   1 &&  0 -> 0
   1 &&  1 -> 1
   2 &&  1 -> 1
  -1 && -1 -> 1
-100 &&  0 -> 0

   0 ||  0 -> 0
   1 ||  0 -> 1
   0 ||  1 -> 1
  -1 ||  0 -> 1
-100 || 20 -> 1

C11 (n1570) §6.5.13 al 3 p 99 say : C11(n1570)§6.5.13al3 p 99说:

The && operator shall yield 1 if both of its operands compare unequal to 0; 如果&&运算符的两个操作数都不等于0,则它将产生1; otherwise, it yields 0. 否则,它产生0。

-1 is a nonzero value, so -1 && -1 is 1 . -1是非零值,因此-1 && -11

On the MSDN page for && : &&MSDN页面上

The logical-AND operator produces the value 1 if both operands have nonzero values. 如果两个操作数都具有非零值,则逻辑AND运算符将生成值1。

Clearly both operands are -1 in your example so they will produce 1. 显然,在您的示例中,两个操作数都为-1,因此它们将生成1。

On the same page, listed for || 在同一页面上,列出了||

If either operand has a nonzero value, the result is 1. 如果任一操作数具有非零值,则结果为1。

In your case one operand is -1, therefore the result is 1 在您的情况下,一个操作数为-1,因此结果为1

AND returns 1 if both operands have non-zero values. 如果两个操作数都具有非零值,则AND返回1。 OR returns 1 if either operand has a non-zero value. 如果任一操作数具有非零值,则OR返回1。

运算符ie(&&)只有在两个条件都为真的情况下才会继续运行,如果是运算符,则运算符即(||)如果两个条件中的至少一个为真,则继续运行。

逻辑运算符返回0或1.如果&&运算符的两个操作数都不是0.Else,它返回0.返回0.语句如if(x),while(x)等。如果参数不是0,则执行。对于所有其他+ ve和-ve参数,它将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM