sourabh912 sourabh912 - 3 years ago 200
C Question

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download