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:

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 equal to(==) operator is confusing for some people because it resembles the assignment operator. They are not the same. The equality operator is equal 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.

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 is not equal to B" then the output of equality expression in "if block”  will be true.

This will print “A is not equal to B”.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag