C++ Logical Operators

Introduction

The logical operators perform logical and, or, and negation operations on their operands.

The first is the && operator, which is a logical AND operator.

The result of a logical AND condition with two operands is true if both operands are true.

Example:

#include <iostream> 

int main() /*from  w w w  .j  a va2  s .c o  m*/
{ 
    bool a = true; 
    bool b = true; 
    if (a && b) 
    { 
        std::cout << "The entire condition is true."; 
    } 
    else 
    { 
        std::cout << "The entire condition is false."; 
    } 
} 

The next operator is ||, which is a logical OR operator.

The result of a logical OR expression is always true except when both operands are false.

Example:

#include <iostream> 

int main() // w w w  . j  av a 2  s  .c o m
{ 
    bool a = false; 
    bool b = false; 
    if (a || b) 
    { 
        std::cout << "The entire condition is true."; 
    } 
    else 
    { 
        std::cout << "The entire condition is false."; 
    } 
} 

The next logical operator is the negation operator represented by a !.

It negates the value of its only right-hand-side operand.

It turns the value of true to false and vice- versa.

Example:

#include <iostream> 

int main() /*  w ww .  j a  v a 2s  .c o m*/
{ 
    bool a = true; 
    if (!a) 
    { 
        std::cout << "The condition is true."; 
    } 
    else 
    { 
        std::cout << "The condition is false."; 
    } 
} 



PreviousNext

Related