C++ Equality Operators

Advertisements
Advertisements

In C++ programs sometimes we need to check for equality of two variables or two expressions. The result of which is a boolean value such as true or false. The equality operators help us compare two numbers or expressions.

This will change the flow of the program in different directions. There are two equality operators:

Equality OperatorsDescription
==Is equal to
!=Is not equal to

The equality operators are similar to relational operators, but they are not part of relational operators. The working of equality operator is to check the equality and nothing else.

The is \hspace{3px} equal \hspace{3px} to(==) operator is confusing for some people because it resembles the assignment operator. They are not the same. The equality operator is \hspace{3px} equal \hspace{3px} to(==) cannot be used to assign a value, this will result in a compilation error.

Example Program: Is equal to (==)

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    //Variable declaration
    
    int a, b, c;
    
    //Variable initialization
    
    a = 200;
    b = 300;
    c = 200;
    
    //Expression with eqaulity operator
    
    if( a == c)
    {
        cout << "A is equal to C" << "\n";
    }
    else
    {
        cout << "A is not equal to C"<< "\n";
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

A is equal to C

In the above example, the result of the equality expression is true.

Advertisements

Example Program: Is not equal to (!=)

The is not equal to (!=) can also output two Boolean value – true or false depending on the expression.

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    //Variable declaration
    
    int a, b, c;
    
    //Variable initialization
    
    a = 200;
    b = 300;
    c = 200;
    
    //Expression with eqaulity operator
    
    if( a != b)
    {
        cout << "A is not equal to B" << "\n";
    }
    else
    {
        cout << "A is equal to B"<< "\n";
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

A is not equal to B

Now, we have modified the previous program slightly and if  A \hspace{3px} is \hspace{3px} not \hspace{3px} equal \hspace{3px}to \hspace{3px}B meaning a != b is true statement, then the output of equality expression in "if \hspace{3px}block" will be executed.

This will print "A \hspace{3px}is \hspace{3px}not \hspace{3px} equal\hspace{3px} to\hspace{3px} B".

Bestseller

Let Us C++

One of the best selling book in C++ programming language. A perfect book for beginners and people who want to prefer self-study in step by step manner. Simple and easy narration style made this book very popular. The book assumes that you don’t have programming experience and starts with basic to more advanced topics.

Advertisements
Advertisements
Advertisements