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

6 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
4

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.

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

9

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

and operator i.e (&&) will proceed only if both the conditions are true , wheree as in the case of or operator i.e(||) will proceed if atleast one of he two condition is true..

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest