Logical AND and OR in c

In && b, this returns true if both a and b are equal to 1. If a = -1 and b = -1, then the expression also returns true. Similarly, with || b, where a = -1 and b = 0, it returns true. Can someone explain the reason.

+4
source share
6 answers

a && b returns 1 when both a and b are nonzero , and not only when they are equal to 1. Otherwise, it returns 0.

a || b a || b returns 1 when at least one of a or b is nonzero , and not just when one of them is 1. Otherwise, it returns 0.

To give a few 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 
+14
source

C11 (n1570) ยง6.5.13 al 3 p 99 say:

& & operator must give 1 if both its operands are compared not equal to 0; otherwise gives 0.

-1 is a nonzero value, so -1 && -1 is 1 .

+9
source

On the MSDN page for && :

The logical-AND operator creates a value of 1 if both operands have non-zero values.

Obviously, both operands are -1 in your example, so they will create 1.

On the same page specified in ||

If any operand has a nonzero value, the result is 1.

In your case, one operand is -1, so the result is 1

+2
source

And returns 1 if both operands have non-zero values. OR returns 1 if any operand has a nonzero value.

+1
source

and operator, i.e. (& &), will only act if both conditions are true, because in the case of either the ie (||) operator it will act if at least one of the two conditions is true.

+1
source

Logical operators return either 0 or 1. The & & operator returns 1, if both its operands are not 0.Else, it returns 0. such as if (x), while (x), etc. executed if its argument is not 0. For all other arguments + ve and -ve, it is executed.

0
source

All Articles