C++ Logical Operators

In this lesson, you will learn about Logical Operators in C++, their usage, and examples to better understand the topic.


What are Logical Operators?

Logical operators are frequently employed in decision-making in C++. Logical operators evaluate whether an expression is true or false. When an expression is true, it returns a result of 1, but when it is false, it returns a result of 0. Let’s look at the following examples to help you better comprehend the logical operators:

Logical Operator Example
&& (Logical AND) Statement 1 && Statement2
|| (Logical OR) Statement1|| Statement 2
! (Logical Not) !Statement

Example

#include <iostream>

using namespace std;
int main() {
  bool output;
  output = (100 != 200) && (100 < 200); // true
  cout << "(100 != 200) && (100 < 200) is true =" << output << endl;
  output = (100 == 200) && (100 < 200); // false
  cout << "(100 == 200) && (100 < 200) is false =" << output << endl;
  output = (100 == 200) && (100 > 200); // false
  cout << "(100 == 200) && (100 > 200) is false =" << output << endl;
  output = (100 != 200) || (100 < 200); // true
  cout << "(100 != 200) || (100 < 200) is true =" << output << endl;
  output = (100 != 200) || (100 > 200); // true
  cout << "(100 != 200) || (100 > 200) is true =" << output << endl;
  output = (100 == 200) || (100 > 200); // false
  cout << "(100 == 200) || (100 > 200) is false =" << output << endl;
  output = !(200 == 50); // true
  cout << "!(200 == 50) is true =" << output << endl;
  output = !(200 == 200); // false
  cout << "!(200 == 200) is false =" << output << endl;
  return 0;
}

Output

(100 != 200) && (100 < 200) is true =1
(100 == 200) && (100 < 200) is false =0
(100 == 200) && (100 > 200) is false =0
(100 != 200) || (100 < 200) is true =1
(100 != 200) || (100 > 200) is true =1
(100 == 200) || (100 > 200) is false =0
!(200 == 50) is true =1
!(200 == 200) is false =0

This concludes the C++ Logical Operators lesson. In the next lesson, you will learn about Flow Control in C++.