-11

I am a beginner C programmer and I was working with Logical Operators recently.

Is the logical or (||) zero whenever both operands are zero. Or is the working somewhat different?

How does it work ? Can someone please explain in detail!

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740

2 Answers2

14
TRUE  || TRUE  == TRUE
TRUE  || FALSE == TRUE
FALSE || TRUE  == TRUE
FALSE || FALSE == FALSE

In C a zero value is FALSE and anything non-zero is TRUE

Also if the left-hand expression of the || evaluates to TRUE, the right-hand expression is not evaluated.

Jimbo
  • 4,352
  • 3
  • 27
  • 44
4

The result of a logical OR (|| operator in C) is true if EITHER of its inputs is true. Similarly logical AND (&& operator in C) is true if BOTH of its inputs are true.

A  B   A OR B   A AND B
0  0     0        0
0  1     1        0
1  0     1        0
1  1     1        1

(Note that 0 is FALSE and anything else is TRUE, 1 is conventionally used in truth tables like the above).

By combining these operators and the logical negation operator (! in C) you can create any operation you want, for example "exclusive OR" (which is true if exactly 1 of its inputs is true) can be written as (A || B) && !(A && B).

Note that in C there is no guarantee that both sides of the operator will be evaluated if it's not necessary - for example if the left hand side of the && operator evaluates to false, there is no point evaluating the right hand side.

Vicky
  • 12,934
  • 4
  • 46
  • 54