GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

Logical operators in C

Logical operators give the answer in the form of true or false only. These operators are used to connect one or more conditions. There are three logical operators in C.

  1. Logical NOT (!)
  2. Logical AND (&&)
  3. Logical OR(||)

You may refer the video as posted at the end.

Logical NOT(!)

  • It is a unary operator.
  • The logical NOT (!) operator gives answer as true, if the input is false, and the answer as false if the input is true.

Truth Table:

truth table NOT

Examples:

  1. !1 = 0
  2. !0 = 1
  3. !-1 = 0 (since -1 is true)
  4. !19 = 0 (since 19 is true)
  5. !’A’ = 0 (Since ‘A’ is true)

We have already discussed about truth and falsity values in C here

Logical AND (&&)

  • It is a binary operator.
  • This operator gives the answer as true if both the operands are true, else the output is false.

Truth Table

logical AND truth table

Examples:

  1. 23 && -4 = 1, (since 23 is True and -4 is also True)
  2. ‘A’ && 21 = 1, (since ‘A’ is True and 21 is also True)
  3. 9 && 0 = 0

We have already discussed about truth and falsity values in C here

Short circuiting in Logical AND

If the first operand in logical AND is false, the compiler doesn’t evaluate the second operator, because FALSE && Anything = FALSE. This is called as short circuiting in logical AND.

Example:

Let a = 0 and b = 4

c = a && ++b,

The values of 

a = 0, b = 4 and c = 0

Note: the expression ++b won’t be evaluated as the first operand in Logical AND is false.

Logical OR (||)

  • It is a binary operator.
  • This operator gives the answer as true if anyone of the operands is true, else the output is false.

Truth Table

truth table or logical

Examples:

  1. 23 || -4 = 1, (since 23 is True and -4 is also True)
  2. ‘A’ || 21 = 1, (since ‘A’ is True and 21 is also True)
  3. 9 || 0 = 1
  4. 0||0 = 0

We have already discussed about truth and falsity values in C here

Short circuiting in Logical OR

If the first operand in logical OR is true, the compiler doesn’t evaluate the second operator, because TRUE && Anything = TRUE. This is called as short circuiting in logical OR.

Example:

Let a = 1 and b = 4

c = a || ++b,

The values of 

a = 1, b = 4 and c = 1

Note: the expression ++b won’t be evaluated as the first operand in Logical OR is true.

Scroll to Top