Computer scienceProgramming languagesC++Operators and expressions

Logical operators

2 minutes read

Logical operators are an integral part of programming languages, including C++. They allow programmers to create complex conditions and control the flow of their programs. In this topic, you will delve into the world of logical operators in C++, exploring their types, and applications. By the end of this topic, you will have a solid understanding of how logical operators work and how to use them effectively in your C++ programs.

Understanding logical operators

Logical operators in C++ are symbols that allow you to perform logical operations on one or more conditions, resulting in a Boolean value (true or false). C++ provides three primary logical operators: AND, OR, and NOT. These operators enable programmers to combine, negate, or evaluate multiple conditions, making complex decision-making easier.

1. AND Operator (&&):

The AND operator, represented by &&, returns true if both operands are true; otherwise, it returns false. Programmers frequently use this operator when they need to satisfy multiple conditions simultaneously. Let's take an example:

bool weatherIsRainy = true;
bool umbrellaAvailable = false;

if (weatherIsRainy && umbrellaAvailable) {
    cout << "You can go outside with an umbrella.";
} else {
    cout << "It's rainy, but you don't have an umbrella.";
}

// Output: It's rainy, but you don't have an umbrella. 

In this example, the condition (weatherIsRainy && umbrellaAvailable) checks whether it's raining and you have an umbrella. If both conditions are true, you can go outside with an umbrella; otherwise, you can't.

Let's see the boolean table of all possible combinations of the AND operator:

Table showing possible combinations of AND operator

Note that for the AND operator, you will get true only in one case, when all values are true.

2. OR Operator (||): The OR operator, denoted by ||, returns true if at least one of the operands is true. It is useful for situations where you want to take action if any of several conditions are met. Let's look at an example of OR operator:

bool hasRaincoat = true;
bool hasUmbrella = false;

if (hasRaincoat || hasUmbrella) {
    cout << "You can handle the rain with a raincoat or umbrella.";
} else {
    cout << "You might get wet since you don't have a raincoat or umbrella.";
}

// Output: You can handle the rain with a raincoat or umbrella. 

The condition (hasRaincoat || hasUmbrella) checks whether you have a raincoat or an umbrella. If you have at least one of these items, you're prepared to handle the rain; otherwise, you might get wet.

Let's see the boolean table of all possible combinations of the OR operator:

Table showing possible combinations of OR operator

Note that for the OR operator, you will get false only in one case, when all values are false.

3. NOT Operator (!): The NOT operator, indicated by !, is a unary operator that negates the value of its operand. If the operand is true, the NOT operator makes it false, and vice versa. It is commonly used to invert conditions. Let's see how the NOT operator behaves in the below example:

bool rainyCondition = true;

if (!rainyCondition) {
    cout << "It's not rainy, so you don't need an umbrella.";
} else {
    cout << "It's rainy, so consider taking an umbrella.";
}

// Output: It's rainy, so consider taking an umbrella. 

In this example, even though the rainyCondition variable is initially set to true, the use of the logical NOT operator (!) in the if statement negates the condition, causing the program to output that it's rainy, and one should consider taking an umbrella.

Let's see the boolean table of all possible combinations of the NOT operator:

Table showing possible combinations of NOT operator

Note that the NOT operator inverts the operand value, as shown in the above table.

Combining logical operators

C++ allows developers to combine logical operators to create complex conditions. You can use parentheses to control the order of evaluation, ensuring that conditions are combined in the desired manner. Combining logical operators is fundamental for expressing intricate decision-making logic in programming.

Developers often use logical operators to combine multiple conditions in if statements and loops. For example:

if (age >= 18 && hasID) {
    // Allow entry
}

In this case, the logical AND operator ensures that both conditions (age >= 18 and hasID) must be true for the code block to execute.

Let's take another example to understand the combining of logical operators:

bool weatherIsRainy = true;
bool umbrellaAvailable = true;
bool isItRaining = true;

if (isItRaining && !umbrellaAvailable) {
    cout << "It's raining and you don't have an umbrella. Stay indoors.\n";
} else if ((weatherIsRainy || !isItRaining) && umbrellaAvailable) {
    cout << "It's a rainy weather or not raining, and you have an umbrella. You can go outside.\n";
} else {
    cout << "Conditions don't match any specific case.\n";
}

// Output: It's a rainy weather or not raining, and you have an umbrella. You can go outside.

Examples

Let's discuss some more examples to understand how you can use the logical operators:

#include <iostream>
using namespace std;

int main() {
    int orderTotal = 120;
    bool isPrimeMember = true;

    if (orderTotal >= 100 || isPrimeMember) {
        cout << "You qualify for a discount!";
    } else {
        cout << "No discount available.";
    }

    return 0;
}

// Output: You qualify for a discount! 

Here, the || (OR) operator checks whether the orderTotal is at least $100 or the customer is a isPrimeMember. If either condition is true, the program informs the customer that they qualify for a discount.

Let's take an example to check whether a student needs to study for tomorrow's examination or not:

#include <iostream>
using namespace std;

int main() {
    bool hasExamTomorrow = true;
    bool isTired = false;

    if (!hasExamTomorrow || isTired) {
        cout << "Take a break and relax!\n";
    } else {
        cout << "Keep studying for your exam.\n";
    }

    return 0;
}

// Output: Keep studying for your exam.

In this example, the ! (NOT) operator and the || (OR) operator are combined. If there's no exam tomorrow (!hasExamTomorrow) or the student is tired (isTired), the program suggests taking a break. Otherwise, it advises continuing to study for the exam.

Now, let's discuss some other examples that you might get through while writing C++ programs:

#include <iostream>

int main() {
    bool a = true;
    bool b = false;
    
    bool result = a && b; // Logical AND
    
    std::cout << "a && b: " << result << std::endl;
    
    return 0;
}

Here's the output of the above code snippet:

a && b: 0

By default, when you output a boolean value using std::cout, it is displayed as either 1 for true or 0 for false. However, using std::boolalpha manipulator changes this behavior. When you apply std::boolalpha to the stream, boolean values are displayed as true or false instead of the numerical values 1 or 0. Let's see in the below example:

#include <iostream>

int main() {
    bool myBool = true;
    
    std::cout << "Default output: " << myBool << std::endl; // Outputs: 1
    
    std::cout << std::boolalpha; // Apply boolalpha manipulator
    
    std::cout << "boolalpha output: " << myBool << std::endl; // Outputs: true
    
    return 0;
}

Conclusion

In C++, logical operators provide the foundation for making decisions based on conditions. By mastering these operators, programmers can create sophisticated logic flows that control program behavior. The AND (&&), OR (||), and NOT (!) operators enable developers to test multiple conditions, combine them effectively, and invert boolean values as needed. Understanding these operators is essential for writing efficient and well-structured code.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo