top

Search

C Tutorial

.

UpGrad

C Tutorial

Logical Operators in C

Logical Operators in C are used to perform logical operations on a given logical expression. They are unary or binary operators, depending on the number of operands (conditions) they act upon, and evaluate the expression to 1 (True) or 0 (False). They are used for decision-making, often in conditional statements. 

Let’s dive in to grasp a deeper insight into the world of logical operators and their implementations. 

Types of Logical Operators in C

In C programming language, we have three logical operators:

  • Logical NOT (!)

  • Logical AND (&&)

  • Logical OR (||)

We will see the function of each of these logical operators in detail and understand their working with the help of their Truth Table. We will also see example snippets for each of them, which helps us understand their usage in C.

Functions of Logical Operators in C

Logical NOT (!) operator

The logical NOT operator, represented as ‘!’, is a unary logical operator in C. It is also called a negation operator, which means it takes the input operand and negates it. If the input is 1 (True), the result will be 0 (False). If the input is 0 (False), the result will be 1 (True).

Truth Table for Logical NOT operator

X

! (X)

0

1

1

0

Logical AND (&&) Operator

The logical AND operator, represented as ‘&&’, is a binary logical operator in C. It takes two input operands and evaluates the result as True if both the input operands are True. It returns False in every other scenario.

Truth table for Logical AND Operator

X

Y

X&&Y

0

0

0

0

1

0

1

0

0

1

1

1


Logical OR (||) Operator

The logical OR operator, represented by ‘||’, is a binary logical operator in C. It takes two input operands and evaluates the result as True if at least one of them is True. It returns False only if both the input operands are False.

Truth table for Logical OR Operator

X

Y

X||Y

0

0

0

0

1

1

1

0

1

1

1

1

Examples Of Logical Operators In C

Logical NOT (!) Operator

Syntax: 

!(condition)

Example:

// C program to illustrate Logical NOT operator

#include<stdio.h>

int isUserSignedIn() {
    // 0 indicates False suggesting user is not signed in
    return 0;
}

int main(){

    // Logical NOT operator is used here
    // If the user is NOT signed in, we can prompt them to sign in to continue
    if ( !isUserSignedIn() ) {
        printf("Please sign in to continue..\n");
    } else {
        printf("Sign In completed. Let's learn about logical operators in C\n");
    }

}

Output:

Please sign in to continue..

Logical AND (&&) Operator

Syntax: 

(condition1 && condition2)

Example:

// C program to illustrate Logical AND operator

#include<stdio.h>

int main(){

    int a = 8, b = 10;

    // Modulo 2 returns the reminder upon division by 2
    // 0 means the number is divisible by 2 (even), 1 means the number is not divisible by 2 (odd)
    if ( (a % 2 == 0) && (b % 2 == 0) ) {
        printf("%d and %d are both even numbers\n", a, b);
    } else {
        printf("%d and %d are not both even numbers\n", a, b);
    }

    // Modulo 4 returns the reminder upon division by 4
    // 0 means the number is divisible by 4, any other value means it's not divisible by 4
    if ( (a % 4 == 0) && (b % 4 == 0) ) {
        printf("%d and %d are both divisible by 4\n", a, b);
    } else {
        printf("%d and %d are not both divisible by 4\n", a, b);
    }

}

Output:

8 and 10 are both even numbers
8 and 10 are not both divisible by 4

Logical OR (||) Operator

Syntax: 

(condition1 || condition2)

Example:

// C program to illustrate Logical OR operator

#include<stdio.h>

int main(){

    int isGameCompleted = 1, isGameExited = 0;

    // Display Thank You message if user completed game or exits the game
    if ( isGameCompleted || isGameExited ) {
        printf("Thank You for playing\n");
    }

    int mathsMarks = 85, scienceMarks = 81;
    // Student is eligible for Science Group if either maths or science marks is >= 90
    // The logical expression evaluated result is stored in isEligibleForScienceGroup as 0 or 1 based on condition
    int isEligibleForScienceGroup = (mathsMarks >= 90 || scienceMarks >= 90);

    if (isEligibleForScienceGroup) {
        printf("Congratulations, you are eligible for Science Group\n");
    } else {
        printf("Sorry, you are not eligible for Science Group\n");
    }

}

Output:

Thank You for playing
Sorry, you are not eligible for Science Group

Short-Circuiting In The Case Of Logical Operators In C

In some scenarios, the C compiler skips the evaluation of parts of a logical expression when it is able to determine the result without fully evaluating it. This is known as Short-circuiting in C. This kind of behaviour can be observed while evaluating the logical AND & logical OR operators. Let us take a look at a few examples.

// C program to illustrate short-circuiting with Logical OR operator

#include<stdio.h>

int main(){

    int a = 1;
    int b = 0;

    if ( a || b ) {
        printf("The condition evaluates to True\n");
    } else {
        printf("The condition evaluates to False\n");
    }

}

Output:

The condition evaluates to True

In the above code, we are using the logical OR condition with two operands 1 and 0. We know that logical OR evaluates to True if any one of the input operands is True. With 1 being the first operand, the C compiler is able to optimise the execution and skip evaluating the second operand 0, as this value is immaterial to the final result of the expression.

This scenario can be better understood with the below example, where the value of the variable is being updated within the condition

// C program to illustrate short-circuiting with Logical OR operator

#include<stdio.h>

int main(){

    int a = 3;
    int b = 5;

    if ( --a > 1 || ++b > 2 ) {
        printf("The condition evaluates to True\n");
    } else {
        printf("The condition evaluates to False\n");
    }

    printf("The value of a: %d\n", a);
    printf("The value of b: %d\n", b);

}

Output:

The condition evaluates to True
The value of a: 2
The value of b: 5

In the above example, we are decrementing the value of variable ‘a’ and incrementing the value of variable ‘b’ within the conditional statement. The first condition, --a > 1 decrements the value of ‘a’ to 2 and compares 2 > 1, which returns True. As OR operator evaluates to True if at least one of the operands is True, the second condition ++b > 2 need not be evaluated. This can be seen in the final print of the output, where the value of ‘a’ is decremented, but the value of ‘b’ remains unchanged. 

Let us take a look at a similar code but with the first condition evaluating to False so that there is no short-circuit taking place

// C program to illustrate short-circuiting with Logical OR operator

#include<stdio.h>

int main(){

    int a = 3;
    int b = 5;

    if ( --a > 5 || ++b > 2 ) {
        printf("The condition evaluates to True\n");
    } else {
        printf("The condition evaluates to False\n");
    }

    printf("The value of a: %d\n", a);
    printf("The value of b: %d\n", b);

}

Output:

The condition evaluates to True
The value of a: 2
The value of b: 6

The above code snippet is similar to the previous one except that the first condition evaluates to False. This causes the compiler to evaluate the second condition as well, which is True and hence the final result is True. The final print shows that both the variables’ values are updated.

Let us also look at one final short-circuit scenario for the logical AND operator

// C program to illustrate short-circuiting with Logical AND operator

#include<stdio.h>

int main(){

    int a = 10;
    int b = 20;

    if ( ++a == 9 && --b > 10 ) {
        printf("The condition evaluates to True\n");
    } else {
        printf("The condition evaluates to False\n");
    }

    printf("The value of a: %d\n", a);
    printf("The value of b: %d\n", b);

}

Output:

The condition evaluates to False
The value of a: 11
The value of b: 20

Precedence and Associativity of Logical Operators In C

In C, all logical operators have left-to-right associativity, meaning that when multiple operands are given as input to the same logical operator, the order of evaluation is from left to right. For example, consider the logical expression a || b || c, first, the leftmost operands a || b is evaluated, and the result of this is chained to the next operand, i.e. ( (a || b) || c ).

The precedence of the logical operators is the order in which each operator is executed. These are crucial to understand when multiple logical operators are being used in a single logical expression. The order from highest to lease precedence is:

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

Practice Problems On Logical Operators In C

In order to revise all the logical operator concepts that we’ve been through so far, let’s explore a few practice problems! The output for each of the questions is given below:

// C practice programs

#include<stdio.h>

int main(){

    int a = 4, b = 6;

    // Q1
    if ( a == 4 && b == 6) {
        printf("Q1: The condition is True\n");
    } else {
        printf("Q1: The condition is False\n");
    }

    // Q2
    if ( a > 0 && b > a && 1 == 0) {
        printf("Q2: The condition is True\n");
    } else {
        printf("Q2: The condition is False\n");
    }

    a = 1;
    b = 1;

    // Q3
    printf("Q3: Result = %d\n", !(a && b));

    // Q4
    if (a > b || (a + 4) > b) {
        printf("Q4: The condition is True\n");
    } else {
        printf("Q4: The condition is False\n");
    }

    // Q5
    if ( !(a && !b) ) {
        printf("Q5: The condition is True\n");
    } else {
        printf("Q5: The condition is False\n");
    }

    // Q6
    if ( !a || b) {
        printf("Q6: The condition is True\n");
    } else {
        printf("Q6: The condition is False\n");
    }

    // Q7
    if( a || b && 0 ) { // Operator precedence - && evaluates before ||
        printf("Q7: The condition is True\n");
    } else {
        printf("Q7: The condition is False\n");
    }

    // Q8
    a = 5;
    b = 5;

    int c = ( a == b  || ++a > 8 ); // Short Circuiting

    printf("Q8: a: %d, b: %d, c: %d\n", a, b, c);
}

Output:

Q1: The condition is True
Q2: The condition is False
Q3: Result = 0
Q4: The condition is True
Q5: The condition is True
Q6: The condition is True
Q7: The condition is True
Q8: a: 5, b: 5, c: 1

Conclusion

This tutorial has covered the basics of logical operators in C, along with various examples and practice problems to test your understanding. With the right resources, learning material, and a decent amount of practice, you can master the C programming language.

Keep exploring and going through more C programs to enhance your skills!

While practising using online material is an excellent way to strengthen your programming skills, higher education can be a great addition to your skill set. 

Check out upGrad’s Master of Science in Computer Science offered by Liverpool John Moores University, a globally recognised university with guidance from industry experts and leading faculties. The course allows you to specialise in Software Development using languages like Java & Python. Throughout the course, students are provided with extensive support through video tutorials, case studies, real projects and live sessions, helping to gain a competitive edge!

FAQs

1.  What happens when the value of a logical expression is assigned to a variable?
A logical expression returns integer 0 to indicate False and a non-zero value (1) to indicate True.

2. What is the precedence of logical operators in C?
The precedence of logical operators is as follows:
     Logical NOT > Logical AND > Logical OR.

3. What is the Truth Table for a logical operator?
The Truth Table of a logical operator helps us understand the operator's working. It gives us the result for all possible combinations of input operands.

Leave a Reply

Your email address will not be published. Required fields are marked *