Trusted answers to developer questions

What are the logical operators "and", "or", and "not" in C++?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A logical operator is a symbol or word that connects two or more expressions so that the value of the produced expression created is solely determined by the value of the original expressions and the operator’s meaning.

Following are the logical operators available in C++:

  • and
  • or
  • not

Description

The table below explains each of the logical operators in C++.

Operator Symbol

Operator Name

Example

Description

&&

Logical And

Operand-A && Operand-B

It returns True, when both the operand-A and operand-B is True, otherwise it returns False.

||

Logical Or

Operand-A || Operand-B

It returns True, when either the operand-A or operand-B is True, otherwise it returns False.

!

Logical Not

! Operand-A

It returns the operand's logical state in reverse.

The following figure is the visual representation of the logical operators in C++.

Visual representation of Logical Operators in C++

Note:

  • True equates to 1.
  • False equates to 0.

Code

The following code illustrates how to use these logical operators in C++.

#include <iostream>
using namespace std;
int main()
{
int A=10, B=20, C=30;
//And Operator
//Both True
cout<<"The value of (A<B && B<C): "<< (A<B && B<C) << "\n";
//First operand: True Second Operand: False
cout<<"The value of (A<B && B>C): "<< (A<B && B>C) << "\n";
//Both False
cout<<"The value of (A>B && B>C): "<< (A>B && B>C) << "\n";
//OR operator
//Both True
cout<<"The value of (A<B || B<C): "<< (A<B || B<C) << "\n";
//First operand: True Second Operand: False
cout<<"The value of (A<B || B>C): "<< (A<B || B>C) << "\n";
//Both False
cout<<"The value of (A>B || B>C): "<< (A>B || B>C) << "\n";
//Not operator
bool D=true;
//reverse of true logical state
cout<<"The value of (!D): "<< (!D) << "\n";
return 0;
}

RELATED TAGS

c++
logicaloperator
Did you find this helpful?