C++ - logical operators - Programming Languages

Understanding C++ Logical Operators

Simple conjunctions like “and” and “or” allow us to connect our ideas — even the most complex ones. 

These two powerful words can play just as big of a role in the C++ programming language, where they’re used as logical operators.

Logical operators are vital in creating a more complex and dynamic control flow of a program. This article breaks down how to create logical operators and when to use them.

What Are Operators in C++?

Operators are symbols used throughout C++ to perform computations on variables and values. As you study to become a C++ developer, you’ll quickly see that operators play an essential role in areas such as arithmetic, relational and logical (true or false) statements in code.

C++ uses Boolean values to check if relational statements are true or false. Boolean values can only return a 1 (true) or a 0 (false) depending on the result of the comparison. As we’ll see below, we can use these statements in several ways to drive a program towards a specific outcome.

First, let’s examine how we can use relational operators to generate true or false outputs.

Relational Operators

Relational operators, as briefly mentioned above, operate on variables with specific values and yield a Boolean result. They use symbols such as ==, !=, <=, and > to check if two operands are the same, different, greater than or less than each other. These operators will output a 1 if the statement is true and a 0 if false.

Logical Operators

Logical operators operate only on Boolean values (or expressions like relational operators that return Boolean values) and yield a Boolean result of their own. The operators used for logical computation in C++  are !, &&, and ||.

Using Logical Operators in C++?

As we’ll see, logical operators are well suited for checking the validity of two (or more) comparative operations. The operators then output a specific response based on the nature of the operator and whether one or both operands are true. In C++, we often see this in the form of an if/else statement.

Before we can take a closer look at where logical operators often show up in code, we’ll first need to understand the syntax behind them. There are a total of three logical operators:

The ”and” (&&) Operator

The logical “and” operator looks at the operands on either of its sides and returns “true” only if both statements are true. If even just one of the two statements is false, the logical “and” will return false.

Below is a practical example of how we can use the && operator in C++:

#include <iostream>
using namespace std;
 
int main()
{
    cout << "Enter a number: ";
    int num {};
    cin >> num;
 
    if (num > 0 && num <= 10)
        cout << "Your number is between 1 and 10";
    else
        cout << "Your number is not between 1 and 10";
    return 0;
}

Above, we ask the user to provide a number. Our logical “and” operator checks to see if the number is greater than 0 and also less than or equal to 10. If both of these statements are true, the number must fall between 1 and 10, and we can output that this is the case.

If a number of 0 or less, or a number greater than 10 is entered, the program will declare the result “false,” negating the if statement and instead outputting that the number is not between 1 and 10.

The “or” (||) Operator

The logical “or” operator works similarly to the ”and” operator above. The difference is that “or” will return “true” if either the left or the right operand is true. The || operator will only return a false value if both operands are false.

Consider a scenario where picking one of two lucky numbers between 1 and 10 in a game will win us a prize. For this example, we’ll set the lucky numbers to four and eight. We’ll need to create a program in C++ to check for winners:

#include <iostream>
using namespace std;

int main() {
    
 cout << "Enter a number: ";
    int num {};
    cin >> num;
    if(num == 4 || num == 8)
        cout << "You chose a winning number!";
    else
        cout << "Sorry, better luck next time.";
    return 0;
}

When a user comes to play our game, they’re asked to input a number. If they correctly guess either four or eight, they’re notified that they chose a winning number. If the user inputs any other integer value, they’ll have to try again some other time.

The “not” (!) Operator

The “not” logical operator is used to convert a value from true to false, or from false to true. Similarly, if an operand evaluates to true, a logical “not” would cause it to evaluate to false. If an operand evaluates to false, its logical “not” equivalent would be true.

The following example reveals one possible use for the logical “not” operator:

#include <iostream>
using namespace std;
 
int main()
{
    cout << "Enter a number: ";
    int x {};
    cin >> x;
    
    if (!x == 0)
        cout << "You typed a number other than 0";
    else
        cout << "You typed zero";
 
    return 0;
}

This program is set up to return true any time the variable x is not zero. The if statement checks to see if x is equal to 0, which will return false for every number but zero. The ! operator flips the result from false to true, causing the program to output the true result of the if statement:

Enter a number: 786
You typed a number other than 0

When using a logical “not” operator, it’s important to remember that it has a very high level of precedence in C++. The logical “not” executes before comparative operators like equals (==) and greater than (>). When coding with a logical “not”, the programmer must ensure that the program is set up to execute operators in the correct order.

In the below example, we see how failing to do so leads to a problem::

#include <iostream>
using namespace std;
 
int main()
{
    int num1 = 3;
    int num2 = 11;
 
    if (!num1 > num2)
        cout << num1 << " is not greater than " << num2;
    else
        cout << num1 << " is greater than " << num2;
 
    return 0;
}

In this example, the program will first execute the logical ! before performing the comparison. In doing so, the program erroneously returns the following:

3 is greater than 11

To set things right, we’ll need to revise our if statement to the following:

if (!(num1 > num2))

This way, the program performs the relational operation first, followed by the logical “not” to lead us to the correct output.

The Truth Table of Logical Operations

No matter how extensive a logical expression, all boil down to a binary true or false value when evaluated.

Considering only the result of an operand “a,” an operand “b” and the logical operator, we can construct the following table that shows the output of a given logical operation. 

aba && ba || b!a
truetruetruetruefalse
truefalsefalsetruefalse
falsefalsefalsefalsetrue
falsetruefalsetruetrue

This table provides a good way to check your work with logical operations. A program that does not return the listed result for the criteria provided will have a mistake that needs resolution.

Bitwise Operators Versus Logical Operators

Bitwise operators look and function similarly to logical operators but operate solely on integer-type values and not Booleans. Bitwise operators compare two integers on a bit-by-bit basis and output a 1 or a 0 depending on the result of the operation.

For the sake of comparison, a bitwise “and” (&) looks very similar to a logical “and” (&&). Likewise, a bitwise “or” (|) follows the same convention as a logical “or” (||). Fortunately, the bitwise “not” (~) looks significantly different than a logical “not” (!).

Mixing up these operators will lead to compilation errors in your program.

Learn C++ With Udacity

Now that you have a better understanding of logical operators, you’re ready to tackle more of what C++ has in store.

At Udacity, we offer an interactive, expert-led program that takes aspiring C++ developers to the next level. You’ll even put your skills to the test by coding five real-world projects.

Enroll in our C++ Nanodegree program today!