C++ Logical Operators

Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. They are used to combine two different expressions together.

The following are the C++ Logical Operators. Assume X holds the value 1 and Y holds 0

OperatorDescriptionExample
&& (logical and)If both the operands are non-zero, then the condition becomes true.(X && Y) is false
|| (logical or)If any of the two operands are non-zero, then the condition becomes true.(X || Y) is true
! (logical not)Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(X && Y) is true

C++ program for Logical Operators

Let us see the following example to understand logical operators better.

#include <iostream>
using namespace std;

int main()
{
   int a = 7, b = 3, c = 8, d = 6;

  	//both the condition has to be true
   if (a == b && c > d)
      cout << "a equals to b AND c is greater than d, TRUE\n";
   else
      cout << "AND operation is FALSE\n";

  	//any one the condition has to be true
   if (a == b || c > d)
      cout << "a equals to b OR c is greater than d, TRUE\n";
   else
      cout << "OR operation is FALSE\n";

   if (!b)
      cout << "b is zero\n";
   else
      cout << "b is not zero";

   return 0;
}

Output:

AND operation is FALSE
a equals to b OR c is greater than d, TRUE
b is not zero