Learn C++ - C++ Logical Operators






The operators are logical OR, written ||; logical AND, written &&; and logical NOT, written !.

The Logical OR Operator: ||

OR can indicate when one or both of two conditions satisfy a requirement.

The logical OR operator, written ||, combines two expressions into one.

If either or both of the original expressions is true, or nonzero, the resulting expression has the value true.

Otherwise, the expression has the value false.

Here are some examples:

5 == 5 || 5 == 9   // true because first expression is true 
5 > 3 || 5 > 10    // true because first expression is true 
5 > 8 || 5 < 10    // true because second expression is true 
5 < 8 || 5 > 2     // true because both expressions are true 
5 > 8 || 5 < 2     // false because both expressions are false 

Because the || has a lower precedence than the relational operators, you don't need to use parentheses in these expressions.

The following table summarizes how the ||operator works.

The Value of expr1 || expr2

                        expr1 == true       expr1 == false 

  expr2 == true                true                 true 

  expr2 == false               true                 false 

C++ || operator supports the shortcut evaluation.

For example, consider the following expression:

i++ < 6 || i == j

Suppose i originally has the value 10.

C++ won't bother evaluating the expression i == j if the expression i++ < 6 is true, since it only takes one true expression to make the whole logical expression true.





Example

The following code uses the ||operator in an if statement to check for both uppercase and lowercase versions of a character.


#include <iostream> 
using namespace std; 
int main() //from   www  . jav a2s  . c  o  m
{ 
     cout << "Do you wish to continue? <y/n> "; 
     char ch; 
     cin >> ch; 
     if (ch == 'y' || ch == 'Y')             // y or Y 
          cout << "You were warned!\a\a\n"; 
     else if (ch == 'n' || ch == 'N')        // n or N 
          cout << "A wise choice ... bye\n"; 
     else 
         cout << "else"; 
     return 0; 
} 

The code above generates the following result.





Logical AND Operator: &&

The logical AND operator, &&, combines two expressions into one.

The resulting expression has the value true only if both of the original expressions are true.

Here are some examples:

5 == 5 && 4 == 4   // true because both expressions are true 
5 > 3 && 5 > 10    // false because second expression is false 

The following table summarizes how the && operator works.

The Value of expr1 && expr2

                       expr1 == true        expr1 == false 

  expr2 == true               true                 false 

  expr2 == false              false                false 

Example 2

The following code shows how to use &&.


#include <iostream> 
const int SIZE = 6; 
using namespace std; 
int main() /* www . j  ava2s . c  o m*/
{ 
     float naaq[SIZE]; 
     int i = 0; 
     float temp; 
     cout << "First value: "; 
     cin >> temp; 
     while (i < SIZE && temp >= 0) // 2 quitting criteria 
     { 
         naaq[i] = temp; 
         ++i; 
         if (i < SIZE)             // room left in the array, 
          { 
              cout << "Next value: "; 
              cin >> temp;            // so get next value 
          } 
     } 
     return 0; 
} 

The code above generates the following result.

Logical NOT Operator: !

The ! operator negates the truth value of the expression that follows it.

If expression is true, then !expressionis false-and vice versa.

The following code shows how to use the not operator.


#include <iostream>
#include <climits>
using namespace std;
bool is_int(double); 
int main()//from  ww  w .j  a  va2 s .c o m
{
    
    double num;

    cout << "Enter an integer value: ";
    cin >> num;
    while (!is_int(num))    // continue while num is not int-able
    {
        cout << "Out of range -- please try again: ";
        cin >> num;
    }
    int val = int (num);    // type cast
    cout << "You've entered the integer " << val << "\nBye\n";
    return 0;
}

bool is_int(double x)
{
    if (x <= INT_MAX && x >= INT_MIN)   // use climits values
        return true;
    else
        return false; 
}

The code above generates the following result.

Character Function

The following code demonstrates some functions from the cctype family.


#include <iostream>
#include <cctype>              // prototypes for character functions
int main(){
    using namespace std;
    cout << "Enter text for analysis, and type @ to terminate input.\n";
    char ch;  // www. j ava2  s .  c o m
    int whitespace = 0;
    int digits = 0;
    int chars = 0;
    int punct = 0;
    int others = 0;

    cin.get(ch);                // get first character
    while (ch != '@')            // test for sentinel
    {
        if(isalpha(ch))         // is it an alphabetic character?
            chars++;
        else if(isspace(ch))    // is it a whitespace character?
            whitespace++;
        else if(isdigit(ch))    // is it a digit?
            digits++;
        else if(ispunct(ch))    // is it punctuation?
            punct++;
        else
            others++;
        cin.get(ch);            // get next character
    }
    cout << chars << " letters, "
         << whitespace << " whitespace, "
         << digits << " digits, "
         << punct << " punctuations, "
         << others << " others.\n";
    return 0; 
}

The code above generates the following result.

Function to test Characters

The following table summarizes the functions available in the cctype package.

Function NameReturn Value
isalnum()returns true if the argument is alphanumeric (that is, a letter or a digit).
isalpha()returns true if the argument is alphabetic.
isblank()returns true if the argument is a space or a horizontal tab.
iscntrl()returns true if the argument is a control character.
isdigit()returns true if the argument is a decimal digit (0-9).
isgraph()returns true if the argument is any printing character other than a space.
islower()returns true if the argument is a lowercase letter.
isprint()returns true if the argument is any printing character,including a space.
ispunct()returns true if the argument is a punctuation character.
isspace()returns true if the argument is a standard white-space character (that is, a space, formfeed, newline, carriage return, horizontal tab, vertical tab).
isupper()returns true if the argument is an uppercase letter.
isxdigit()returns true if the argument is a hexadecimal digit character (that is, 0-9, a-f, or A-F).
tolower()If the argument is an uppercase character, tolower() returns the lowercase version of that character; otherwise, it returns the argument unaltered.
toupper()If the argument is a lowercase character, toupper() returns the uppercase version of that character; otherwise, it returns the argument unaltered.