C++ Logical operators

C++ provides three logical operators to evaluate the logical operations, which are as follows:

  1. AND (&&)
  2. OR (||)
  3. NOT (!)
Operator
Description
Example
&&
AND
x > 0 && y > 0
||
OR
x > 0 || y > 0
!
NOT
!(x > 0 && y > 0)

Logical AND (&&) operator:

It returns true if and only if both the operands are true.

Example:

bool a = true, b = false;
cout << (a && b) << endl; // Output: 0 (false)

In the above example, the && operator checks if both a and b are true or not. Since b is false, the result of the operation is false.

Logical OR (||) operator:

It returns true if at least one of the operands is true.

Example:

bool a = true, b = false;
cout << (a || b) << endl; // Output: 1 (true)

In the above example, the || operator checks if at least one of a and b is true or not. Since a is true, the result of the operation is true.

Logical NOT (!) operator:

It negates the value of the operand.

Example:

bool a = true;
cout << !a << endl; // Output: 0 (false)

In the above example, the ! operator negates the value of a and returns false, as the original value of a was true.