Logical Operators in C

Logical operators are used when we want to test more than one condition and make decisions. Logical expressions also give 1 (if true), and 0 (if false).

OperatorMeaningDescription
&&logical ANDCompares two test conditions. For example, to test if the number x lies between 10 and 20, the expression will be x > 10 && x <20. Both conditions must be true to satisfy the condition. It results 1 (if true) and 0 (if false).
||logical ORThis condition is satisfied if one of the test conditions is true. For Example to check whether the number x is negative or even the expression will be (x < 0) || (x % 2 == 0)
!logical NOTThis expression is used to reverse the logic. For example, if x is equal to 1 (true), then applying this operator results in 0 (false).
Relational Operators in C

The expression on the left and right-hand sides of the logical operator will be either non-zero(true) or zero (false). We can see all the cases of results of this operator in the form of the truth table.

Operand1Operand2Operand1 && Operand2Operand1 || Operand2!Operand1
00001
0Non-zero011
Non-zero0010
Non-zeroNon-zero110
The truth table for Logical Operators

Whatever the expression is the result will be either 1(true) or 0(false).

Examples:

#include <stdio.h>

int main(){
    int x = 10, y = 12, z = 5;

    // check if x is between 5 and 20
    printf("x > 5 && x < 20 = %d\n", x > 5 && x < 20);
    // check if y is greater than x or divisible by z
    printf("y > x || (y %% z == 0) = %d\n", y > x || (y % z == 0));

    // see the result of negation of x
    printf("!x = %d\n", !x);
    return 0;
}

Expected Output:

x > 5 && x < 20 = 1
y > x || (y % z == 0) = 1
!x = 0