Home | Computer | Logical Operators in C++ | Different Logical Operators

Logical Operators in C++ | Different Logical Operators

August 23, 2022

Logical operators are used to evaluate compound conditions. A logical operator is a binary operation that returns either true or false. Logical operators are commonly used in programming languages to perform boolean operations. In C++,

The following are some examples of logical operators: && (and), || (or), !(Not)

OperatorsNameExampleDescription
&&ANDx < 6 &&  x < 12Returns true if both statements are true
||ORx < 6 || x < 12Returns true if one of the statements is true
!NOT!(x < 6 && x < 12)Reverse the result, returns false if the result is true

Different logical Operators in C++

There are three logical operators in C++

AND Operator (&&)

The symbol used for an operator is (&&). It is used to evaluate two conditions. It produces a true result if both conditions are true. It produces a false result if any one condition is false.

Condition 1OperatorCondition 2Result
False&&FalseFalse
False&&TrueFalse
True&&FalseFalse
True&&TrueTrue

Example

#include <iostream>

using namespace std;

int main()

{

  int x = 6;

  int y = 4;

  cout << (x > 5 && y < 12); // returns true (1) because 6 is greater than 5 AND 6 is less than 12

  return 0;

}

OR Operator (||)

The symbol used for the OR operator is (||). It is used to evaluate two conditions. It gives a true result if either condition is true. It gives false results if both conditions are false.

Condition 1OperatorCondition 2Result
False||FalseFalse
False||TrueTrue
True||FalseTrue
True||TrueTrue

Example

#include <iostream>

using namespace std;

int main() {

  int x = 6;

  int y = 4;

  cout << (x > 5 || y < 3); // returns true (1) because one of the conditions are true (6 is greater than 5, but 4 is not less than 3)

  return 0;

}

NOT Operator (!)

The symbol used for NOT operator is (!). it is used to reverse the result of a condition. It gives true result if the condition is false. It gives false result if the condition is true.

OperatorConditionResult
!TrueFalse
!FalseTrue

Example

#include <iostream>

using namespace std;

int main() {

  int x = 6;

  int y = 4;

  cout << (!(x > 5 || y < 3); // returns False (0), because the condition is true.

  return 0;

}