Logical Operators in C

By | February 18, 2023

Prerequisite – Operators in C
In C, logical operators are used to perform logical operations on expressions that evaluate to either true (nonzero) or false (zero). They are typically used in conditional statements and loops to make decisions based on whether certain conditions are met or not.

Types of Logical Operators in C:
There are three logical operators in C:

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

Here’s a description of each operator and how they work:

  1. Logical AND (&&): This operator returns true (nonzero) if both expressions it connects are true, and false (zero) otherwise. For example, if a and b are both true, a && b will be true, but if one or both are false, a && b will be false. The logical AND operator has higher precedence than the logical OR operator.
  2. Logical OR (||): This operator returns true (nonzero) if at least one of the expressions it connects is true, and false (zero) otherwise. For example, if a is true and b is false, a || b will be true, but if both are false, a || b will be false.
  3. Logical NOT (!): This operator reverses the logical value of its operand. If the operand is true, it returns false (zero), and if the operand is false, it returns true (nonzero). For example, if a is true, !a will be false, and if a is false, !a will be true.

Example:
Here’s an example code that demonstrates the use of logical operators in C:

#include <stdio.h>

int main() {
    int a = 1;
    int b = 0;

    printf("a && b: %d\n", a && b);
    printf("a || b: %d\n", a || b);
    printf("!a: %d\n", !a);
    printf("!b: %d\n", !b);

    return 0;
}

When you run this code, you will see the following output:

a && b: 0
a || b: 1
!a: 0
!b: 1

This output shows the results of using each of the logical operators with the variables a and b. The value of each expression is printed to the console. In this example, a && b evaluates to false because b is false, a || b evaluates to true because a is true, and !a evaluates to false because a is true.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.