Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical AND and OR in c

Tags:

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. Can anybody please explain the reason.

like image 229
sourabh912 Avatar asked Jul 22 '12 12:07

sourabh912


People also ask

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.

Is it && or & in C?

& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & . if you want to use to phrase and you want to treat them logically you can use && .

Is && a logical operator in C?

In C programming language, there are three logical operators Logical AND (&&), Logical OR (||) and Logician NOT (!).

Is || and && the same?

&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true. so it continues till the end to check atleast one condition to become true.


4 Answers

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 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.

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
like image 187
orlp Avatar answered Oct 23 '22 23:10

orlp


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

The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0.

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

like image 36
md5 Avatar answered Oct 23 '22 22:10

md5


On the MSDN page for &&:

The logical-AND operator produces the value 1 if both operands have nonzero values.

Clearly both operands are -1 in your example so they will produce 1.

On the same page, listed for ||

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

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

like image 32
Doug T. Avatar answered Oct 23 '22 23:10

Doug T.


AND returns 1 if both operands have non-zero values. OR returns 1 if either operand has a non-zero value.

like image 41
Wiktor Zychla Avatar answered Oct 23 '22 21:10

Wiktor Zychla