Understanding the Logical OR (||) Operator in C

01 Jul 2023 Balmiki Mandal 0 C Programming

What is the Logical OR (||) Operator in C?

The logical OR (||) operator in C is a binary operator used to perform logical disjunction on two expressions. It will return true if either of the two expressions being evaluated is true. If both expression are false, the OR operator will return false.

The syntax for the OR operator is:

expression1 || expression2

If the value of expression1 is true, then expression2 is not evaluated and the OR operator immediately returns true. This is known as short-circuit evaluation.

For example, the following statement would return true since 10 is greater than 5:

10 > 5 || 2 < 1 

The logical OR operator can be used in conjunction with the logical AND (&&) operator to create more complex conditions. For example, both expressions must be true for the overall condition to evaluate to true. This is know as logical conjunction:

expression1 && expression2 || expression3

In this example, expression1 and expression2 must both be true for expression3 to be evaluated. If either expression1 or expression2 is false, then the OR operator will return false.

The logical OR operator is an important part of C programming, and it should be used with caution and understanding in order to ensure code is accurate and efficient.

 

C program that demonstrates the logical OR (||) operator:

#include <stdio.h>

int main() {
  int a = 10;
  int b = 20;
  int c = 30;

  // The logical OR operator returns 1 if at least one of the operands is true, and 0 if all of the operands are false.
  int result1 = (a == 10) || (b == 20) || (c == 30);
  int result2 = (a == 10) || (b == 30) || (c == 30);

  printf("result1 = %d\n", result1);
  printf("result2 = %d\n", result2);

  return 0;
}

This program will print the following output:

Code snippet
result1 = 1
result2 = 0

The first result1 is 1 because at least one of the conditions, a == 10 or b == 20, is true. The second result2 is 0 because none of the conditions are true.

Here is an explanation of the code:

int a = 10;
int b = 20;
int c = 30;

These lines declare three integer variables: a, b, and c.

// The logical OR operator returns 1 if at least one of the operands is true, and 0 if all of the operands are false.
int result1 = (a == 10) || (b == 20) || (c == 30);
int result2 = (a == 10) || (b == 30) || (c == 30);

These lines assign the results of the logical OR operation to two integer variables, result1 and result2. The first result1 is 1 because at least one of the conditions, a == 10 or b == 20, is true. The second result2 is 0 because none of the conditions are true.

printf("result1 = %d\n", result1);
printf("result2 = %d\n", result2);

These lines print the values of result1 and result2 to the console.

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.