Written version of Logical operators in C++

Can we use keywords in place of operators in C++ ?
Yes, certainly, we can. The ANSI C++ Standard has proposed keywords for several C++ operators . They originated in C in the header at the time when there were keyboards that couldn’t type the required symbols like &&, !, || etc.
In C++, they became alternate token just like regular tokens, except for spelling. So during parsing “and” is exactly the same as “&&”, it’s just a different way of spelling the same thing.

Consider the following expression:

x > y && m != 100,

can be replaced by:

x > y and m not_eq 100



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate 
// logical operator keywords
#include<iostream>
using namespace std;
int main()
{
    int x, y, z;
    x = 1;
    y = 0;
    z = 10;
  
    // Using keywords for || (or), && (and)
    if ((x or y) and y )
    {
        cout << "Hi, we are in if.";
    
  
    // Using keywords for ! (not), || (or), != (not_eq)
    else if (not y or x not_eq z)
    {
        cout << "Hi, we are in else if.";
    }
    return 0;

chevron_right


Output:

Hi, we are in else if.

Similar to this, we can use keywords in place of all the operators mentioned in the table .

Benefits-

  1. Operator keyword enhances the readability of logical expressions.
  2. They are useful in situations when the keyboard doesnot support certain special characters such as &, ~ and ^, so we can use keywords in place of them.

Pitfall: Although, it is a very exciting feature of C++, but one needs to be a bit cautious while using it . Ordinarily, while, using these operators, we can write variables with or without leaving a space before or after these operators, but, when these operators are replaced by keywords, it becomes mandatory to leave a space after and before these keywords, as demonstrated below :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate 
// logical operator keywords
#include<iostream>
using namespace std;
int main()
{
    int x, y;
    x = 1;
      
    // Wrong way to use compl for ~
    // y = complx;
  
    // Right way to use compl for ~
    y = compl x;
  
    cout << y;
    return 0;
}

chevron_right


Output:

-2

Reference-

  1. Object-Oriented Programming with C++ by E. Balagurusamy

This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.