C++ Equality Operators

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:

Advertisements
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
Advertisements

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

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".

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.