C++ Comparison operators

Introduction

Comparison operators allow us to compare the values of operands.

Comparison operators are less than <, less than or equal to <=, greater than >, greater than or equal to >=, equal to ==, not equal to !=.

We can use the equality operator == to check if the values of operands are equal:

#include <iostream> 

int main() //from  w  ww .ja v  a 2  s . c o m
{ 
    int x = 5; 
    if (x == 5) 
    { 
        std::cout << "The value of x is equal to 5."; 
    } 
} 

Use-case for other comparison operators:

#include <iostream> 

int main() //from w  w w. j  a  va  2 s .com
{ 
    int x = 10; 
    if (x > 5) 
    { 
        std::cout << "The value of x is greater than 5."; 
    } 
    if (x >= 10) 
    { 
        std::cout << "\nThe value of x is greater than or equal to 10."; 
    } 
    if (x != 20) 
    { 
        std::cout << "\nThe value of x is not equal to 20."; 
    } 
    if (x == 20) 
    { 
        std::cout << "\nThe value of x is equal to 20."; 
    } 
} 

Now, we can use both logical and comparison operators in the same condition:

#include <iostream> 

int main() //from  w  w w  .  j a v a 2s. c om
{ 
    int x = 10; 
    if (x > 5 && x < 15) 
    { 
        std::cout << "The value of x is greater than 5 and less than 15."; 
    } 
    bool b = true; 
    if (x >5 && b) 
    { 
        std::cout << "\nThe value of x is greater than 5 and b is true."; 
    } 
} 



PreviousNext

Related